This project has moved and is read-only. For the latest updates, please go here.

Deserialize $ref and $id

Mar 7, 2010 at 7:07 PM



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.



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

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

Also posted at:






Mar 17, 2010 at 8:27 AM

The problem is there is additional properties in the $ref object. I've made the error message clearer.