2011-05-10 48 views
2

我寫過一個web服務,它發送並返回使用Json.NET創建的json。我已經包含了允許多態的類型名稱。與bit of hacking,我已經與Silverlight客戶端的工作,但我不知道如何使它的JavaScript客戶端的工作。如何解析Json.NET多態對象?

我該如何解析這個使用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"); 
     } 

    } 
} 
+0

您能在Silverlight中顯示您的反序列化代碼嗎?我很好奇你是如何運作的。到目前爲止,我的嘗試並不奏效。 http://stackoverflow.com/questions/5943764/deserializing-dictionary-with-derived-types-using-newtonsofts-json-library – rboarman 2011-05-10 17:25:04

+0

@rboarman我已經添加了反序列化的代碼。 – 2011-05-10 20:03:51

+0

我就是這樣做的。謝謝 – rboarman 2011-05-10 20:17:31

回答

3

要做實際的解析,可以使用json2.js或JQuery的$ .parseJSON()方法。這些將創建一個JavaScript對象,直接類似於您發送的JSON。由於Javascript是一種腳本語言,你不會再考慮「多態性」,但你應該能夠評估對象的屬性(而不必關心對象的「類型」)如何:

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