我写了一个使用Json.NET创建并发送json的Web服务。我已经包含了类型名称,允许多态性。通过一些技巧, 我已经使它可以在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");
}
}
}