How to parse Json.NET polymorphic objects?
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);
开发者_Go百科 else if (a is Cat)
Debug.WriteLine (((Cat)a).LikesMice);
else
Debug.WriteLine("error");
}
}
}
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;
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.
精彩评论