CodeGo.net>如何解析Json.NET多态对象?
作者:互联网
我编写了一个Web服务,该服务发送和返回使用Json.NET创建的json.我已经包含了允许多态的类型名.有了bit of hacking,我已经可以在Silverlight客户端上使用它,但是我不知道如何使它适用于javascript客户端.
如何使用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直接相似.
由于Javascript是一种脚本语言,因此您不再需要考虑“多态性”,但是您应该能够像这样评估对象的属性(无需关心对象的“类型”):
var obj = $.parseJSON(json);
var firstAnimalName = obj.Animals[0].Name;
标签:json-net,json,javascript,c 来源: https://codeday.me/bug/20191208/2091370.html