Can not deserialize JSON containing $ref keys

ⅰ亾dé卋堺 提交于 2019-12-18 09:10:31

问题


I have the following code trying to deserialize a JSON string and the library gives me this error:

Additional content found in JSON reference object. A JSON reference object should only have a $ref property. Path 'user.obj', line 1, position 34.

Any idea what is wrong? (I understand that it is complaining about the second $ref, but I don't know why.) What is the workaround ?

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; }
}

回答1:


Json.Net uses $ref along with $id as metadata to preserve object references in JSON. So when it sees $ref it assumes that property is not part of the actual JSON property set, but an internal identifier referring to a matching $id somewhere else in the JSON. Since your usage of $ref is different than what Json.Net expects to see, it is throwing an error.

UPDATE

In Json.Net version 6.0.4 and later, there is now a setting by which you can instruct the deserializer to treat these metadata properties as normal properties instead of consuming them. All you need to do is set the MetadataPropertyHandling setting to Ignore and then deserialize as usual.

var settings = new JsonSerializerSettings();
settings.MetadataPropertyHandling = MetadataPropertyHandling.Ignore;

var obj = JsonConvert.DeserializeObject<FormDefinitionList>(json, settings);

Prior to version 6.0.4, a workaround was needed to solve this issue. If you cannot upgrade to the lastest version of Json.Net, see my answer to a similar question for some possible solutions.



来源:https://stackoverflow.com/questions/22299390/can-not-deserialize-json-containing-ref-keys

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!