如何解析Json.NET多态对象? [英] How to parse Json.NET polymorphic objects?

查看:123
本文介绍了如何解析Json.NET多态对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个Web服务,该服务发送和返回使用Json.NET创建的json.我已经包含了允许多态的类型名.有了一点点黑客攻击,我已经在Silverlight客户端上使用了此功能,但我不知道如何使其在javascript客户端上有效.

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.

如何使用javascript解析?

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

这是c#类:

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");
        }

    }
}

推荐答案

要执行实际的解析,可以使用json2.js或JQuery的$ .parseJSON()方法.这些将创建一个JavaScript对象,该对象与您发送的JSON直接相似.

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.

由于Javascript是一种脚本语言,因此您不再考虑多态性",但是您应该能够像这样评估对象的属性(无需关心对象的类型"):

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;

这篇关于如何解析Json.NET多态对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆