Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

json - Deserializing $ref and $id

So I'm trying to deserialize an object that has properties: $ref and $id. I have tried going between Dictionary as well as an object where I have specified namingconventions via JsonPropertyAttribute. Serialization works, but deserialization doesn't. The error I keep getting is:

Additional text found in JSON string after finishing deserializing object.

Sample code where all three samples, fail.

[Serializable]
public class Ref
{
    [JsonProperty(PropertyName = "$ref")]
    public virtual string RefName { get; set; }
    [JsonProperty(PropertyName = "$id")]
    public virtual int Id { get; set; }
}

[Serializable]
public class Child
{
    public virtual string Name { get; set; }
    [JsonProperty(IsReference = true)]
    public virtual Ref Father { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        //Additional text found in JSON string after finishing deserializing object.
        //Test 1
        var reference = new Dictionary<string, object>();
        reference.Add("$ref", "Persons");
        reference.Add("$id", 1);

        var child = new Dictionary<string, object>();
        child.Add("_id", 2);
        child.Add("Name", "Isabell");
        child.Add("Father", reference);

        var json = JsonConvert.SerializeObject(child);
        var obj = JsonConvert.DeserializeObject<Dictionary<string, object>>(json); //Exception

        //Test 2
        var refOrg = new Ref {RefName = "Parents", Id = 1};
        var refSer = JsonConvert.SerializeObject(refOrg);
        var refDeser = JsonConvert.DeserializeObject<Ref>(refSer); //Exception

        //Test 3
        var childOrg = new Child {Father = refOrg, Name = "Isabell"};
        var childSer = JsonConvert.SerializeObject(childOrg);
        var childDeser = JsonConvert.DeserializeObject<Child>(refSer); //Exception
    }
}
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

I have the same issue when trying to deserialize a swagger/json schema document. The solution is:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...