[英]Deserialization of JSON in c#
我有以下JSON
{
"employee" : {
"property1" : "value1",
"property2" : "value2",
//...
}
}
像這樣的班級
public class employee
{
public string property1{get;set;}
public string property2{get;set;}
//...
}
在我的 JSON 中,如果我需要添加 property3,那么我也需要在我的班級中進行更改。 即使我更改了我的 JSON(添加另一個屬性,如 property3),我如何反序列化為一個類。 像newtonsoft.json
這樣的序列化/反序列化技術與類緊密結合。 有沒有更好的方法/工具可以在 c# 的可移植類中deserialize
這些JSON
?
Newtonsoft與強類型並不緊密耦合。 您也可以反序列化動態類型。 請參閱此處的類似問題( 如何在不知道 Key 值的情況下讀取 Json 數據)
你可以試試 .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);
;
}
}
}
如果我們可以使用“Dictionary< string
, string
>employee”上面的json可以反序列化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.