2015-06-22 41 views
2

我有以下JSON反序列化在C#

{ 
    "employee" : { 
     "property1" : "value1", 
     "property2" : "value2", 
     //... 
    } 
} 

一類像

public class employee 
{ 
    public string property1{get;set;} 
    public string property2{get;set;} 
    //... 
} 

在我的JSON,如果我需要添加property3然後我需要在我的課變化太大。 即使如果我更改我的JSON(添加另一個屬性如property3),我如何反序列化到類。 序列化/反序列化技術如newtonsoft.json與Class緊密結合。 有沒有更好的方法/工具deserialize這類JSON在c#中的可移植類?

+1

一種方法是定製JSON-Deserialiter,f.E.看看這裏:http://stackoverflow.com/questions/8030538/how-to-implement-custom-jsonconverter-in-json-net-to-deserialize-a-list-of-base 有點反射魔術,你可以用一個有效的setter來檢查所有的屬性,並通過命名約定將其映射到JSON-Data。 –

+1

您是否想要反序列化爲某種匿名類型,以便您可以讀取數據而不必關心它是什麼類型的對象?如果是的話,牛頓軟件庫會讓你這樣做。 – Chris

+0

這個問題實際上並不是關於反序列化per-sae,它更多地是基於動態輸入數據動態地向C#類添加屬性。 – dougajmcdonald

回答

0

你可以試試。NET的JavaScriptSerializer(System.Web.Script.Serialization.JavaScriptSerializer)。如果某個字段被添加或刪除,它會正常地反序列化對象。

namespace ConsoleApplication8 
{ 
public class Person 
{ 
    public int PersonID { get; set; } 
    //public string Name { get; set; } 
    public bool Registered { get; set; } 
    public string s1 { get; set; } 
} 
class Program 
{ 
    static void Main(string[] args) 
    { 
     var s = "{\"PersonID\":1,\"Name\":\"Name1\",\"Registered\":true}"; 
     var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); 
     var o = serializer.Deserialize<Person>(s); 
     ; 
    } 
} 
} 
0

如果我們可以用 「字典< stringstring>僱員」 上述JSON可以deserilized。