Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...