我有以下代码试图反序列化 JSON 字符串,库给我这个错误:
Additional content found in JSON reference object. A JSON reference object should only have a $ref property. Path 'user.obj', line 1, position 34.
知道哪里出了问题吗? (我知道它在提示第二个 $ref,但我不知道为什么。)解决方法是什么?
void Main()
{
var s = "{\"user\": {\"$ref\": \"123456\", \"obj\": {\"$ref\": \"123456\"}}}";
JsonConvert.DeserializeObject<Root>(s).Dump();
}
// Define other methods and classes here
public class Root
{
[JsonProperty("user")]
public User User { get; set; }
}
public class User
{
[JsonPropertyAttribute("$ref")]
public string Ref { get; set; }
[JsonPropertyAttribute("obj")]
public Obj Obj { get; set; }
}
public class Obj
{
[JsonPropertyAttribute("$ref")]
public string Ref { get; set; }
}
最佳答案
Json.Net 使用 $ref
和 $id
作为元数据来保存 JSON 中的对象引用。因此,当它看到 $ref
时,它假定该属性不是实际 JSON 属性集的一部分,而是引用 JSON 中其他地方匹配的 $id
的内部标识符。由于您对 $ref
的使用与 Json.Net 期望看到的不同,因此它会引发错误。
更新
在 Json.Net 版本中 6.0.4后来,现在有一个设置可以指示反序列化器将这些元数据属性视为普通属性而不是使用它们。您需要做的就是将 MetadataPropertyHandling
设置设置为 Ignore
,然后照常反序列化。
var settings = new JsonSerializerSettings();
settings.MetadataPropertyHandling = MetadataPropertyHandling.Ignore;
var obj = JsonConvert.DeserializeObject<FormDefinitionList>(json, settings);
在版本 6.0.4 之前,需要一种变通方法来解决此问题。如果您无法升级到最新版本的 Json.Net,请参阅 my answer to a similar question一些可能的解决方案。
关于c# - 无法反序列化包含 $ref 键的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22299390/