How to parse Json.NET polymorphic objects?

江枫思渺然 提交于 2019-12-20 02:36:08

问题


I've written a web service that sends and returns json created with Json.NET. I've included typenames, which allows polymorphism. With a bit of hacking, I've got this working with a silverlight client, but I don't know how to make it work for javascript clients.

How can I parse this using 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");
        }

    }
}

回答1:


To do the actual parsing, you can use json2.js or JQuery's $.parseJSON() method. Those will create a javascript object that directly resembles the JSON you sent across.

Since Javascript is a script language, you won't be thinking in terms of "polymorphism" anymore, but you should be able to evaluate properties on the objects (without caring what "type" of object they are) like so:

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



回答2:


Try https://github.com/douglascrockford/JSON-js/blob/master/json2.js. There is a parse function which will parse your string into a javascript object safely.



来源:https://stackoverflow.com/questions/5953450/how-to-parse-json-net-polymorphic-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!