Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }
}
like image 763
Daniel Avatar asked Jul 15 '26 08:07

Daniel


1 Answers

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;
like image 168
Hongye Sun Avatar answered Jul 18 '26 08:07

Hongye Sun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!