Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

c# - Can not deserialize JSON containing $ref keys

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; }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...