2013-03-27 45 views
0

IM使用json.net如何獲取json源的反序列化對象? json.net

JSON的反序列化到對象後,我想這個對象

例如JSON的來源

objParent:{ 
    objChild1: {name:"testObj"}, 
    objChild2: {age: 25} 
} 
在C#代碼

public ObjChild1 
{ 
    public string name {get;set;} 

    [JsonIgnore] 
    public string JsonSource { get; set; } //objChild1: {name:"testObj"} 
} 

public ObjChild2 
{ 
    public int age {get;set;} 

    [JsonIgnore] 
    public string JsonSource { get; set; } //objChild2: {age: 25} 
} 

回答

0

我沒有JSON.NET安裝,但與標準類,你可以簡單地序列化單個對象回JSON字符串,像這樣:

... 
    public static class JSONHelper 
    { 
     public static string ToJSONString(this object obj) 
     { 
      JavaScriptSerializer serializer = new JavaScriptSerializer(); 
      return serializer.Serialize(obj); 
     } 
    } 
... 

    public ObjChild1 
    { 
     public string name {get;set;} 

     [ScriptIgnore] 
     public string JsonSource { get { return this.ToJSONString(); } } 
    }  

    public class ObjChild2 
    { 
     public int age {get;set;} 

     [ScriptIgnore] 
     public string JsonSource { get { return this.ToJSONString(); } } 
    }