How to parse polymorphic Json.NET objects?

I wrote a web service that sends and returns json created using Json.NET. I have included typenames, which allows polymorphism. With hacking , it works for me with the silverlight client, but I don’t know how to make it work for javascript clients.

How can I parse this with javascript?

{
  "$type": "MyAssembly.Zoo, MyAssembly",
  "ID": 1,
  "Animals": [
    {
      "$type": "MyAssembly.Dog, MyAssembly",
      "LikesBones": true,
      "Name": "Fido"
    },
    {
      "$type": "MyAssembly.Cat, MyAssembly",
      "LikesMice": false,
      "Name": "Felix"
    }
  ]
}

Here are the C # classes:

public class Animal
{
    public string Name { get; set; }
}
public class Dog : Animal
{
    public bool LikesBones { get; set; }
}
public class Cat : Animal
{
    public bool LikesMice { get; set; }
}
public class Zoo
{
    public int ID { get; set; }
    private List<Animal> m_Animals = new List<Animal>();
    public List<Animal> Animals { get { return m_Animals; } set { m_Animals = value; } }
    public static void Test1()
    {
        Zoo z1 = new Zoo() { ID = 1 };
        z1.Animals.Add(new Dog() { Name = "Fido", LikesBones = true });
        z1.Animals.Add(new Cat() { Name = "Felix", LikesMice = false });
        var settings = new JsonSerializerSettings();
        settings.TypeNameHandling = TypeNameHandling.Objects;

        string s1 = JsonConvert.SerializeObject(z1, Formatting.Indented, settings);
        Debug.WriteLine(s1);

        var z2 = JsonConvert.DeserializeObject<Zoo>(s1, settings);
        foreach (Animal a in z2.Animals)
        {
            if (a is Dog)
                Debug.WriteLine(((Dog)a).LikesBones);
            else if (a is Cat)
                Debug.WriteLine (((Cat)a).LikesMice);
            else
                Debug.WriteLine("error");
        }

    }
}
+3
source share
2 answers

To do the actual parsing, you can use the json2.js or jQuery $ .parseJSON () method. This will create a javascript object that will look like the JSON you sent.

Javascript script, "", ( , "" ) :

var obj = $.parseJSON(json);
var firstAnimalName = obj.Animals[0].Name;
+3

All Articles