是否有方法将JSON内容反序列化为c#动态类型?为了使用DataContractJsonSerializer,最好跳过创建一堆类。


当前回答

c#有一个轻量级JSON库,叫做SimpleJson。

它支持。net 3.5+, Silverlight和Windows Phone 7。

它支持。net 4.0的动态

它也可以作为NuGet包安装

Install-Package SimpleJson

其他回答

另一种选择是“将JSON粘贴为类”,这样就可以快速轻松地反序列化。

只需复制整个JSON 在Visual Studio中:点击编辑→特殊粘贴→将JSON作为类粘贴

这里有一个更好的解释…“将JSON粘贴为类”NET和Web工具2012.2 RC

使用Json非常简单。NET:

dynamic stuff = JsonConvert.DeserializeObject("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");

string name = stuff.Name;
string address = stuff.Address.City;

同样使用Newtonsoft.Json.Linq:

dynamic stuff = JObject.Parse("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");

string name = stuff.Name;
string address = stuff.Address.City;

文档:使用动态查询JSON

试试这种方法!

JSON的例子:

[{
    "id": 140,
    "group": 1,
    "text": "xxx",
    "creation_date": 123456,
    "created_by": "xxx@gmail.co",
    "tags": ["xxxxx"]
  }, {
    "id": 141,
    "group": 1,
    "text": "xxxx",
    "creation_date": 123456,
    "created_by": "xxx@gmail.com",
    "tags": ["xxxxx"]
}]

c#代码:

var jsonString = (File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(),"delete_result.json")));
var objects = JsonConvert.DeserializeObject<dynamic>(jsonString);
foreach(var o in objects)
{
    Console.WriteLine($"{o.id.ToString()}");
}

JsonFx可以将JSON内容反序列化为动态对象。

序列化动态类型(.NET 4.0的默认值):

var reader = new JsonReader(); var writer = new JsonWriter();

string input = @"{ ""foo"": true, ""array"": [ 42, false, ""Hello!"", null ] }";
dynamic output = reader.Read(input);
Console.WriteLine(output.array[0]); // 42
string json = writer.Write(output);
Console.WriteLine(json); // {"foo":true,"array":[42,false,"Hello!",null]}

简单的“字符串JSON数据”对象,无需任何第三方DLL文件:

WebClient client = new WebClient();
string getString = client.DownloadString("https://graph.facebook.com/zuck");

JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic item = serializer.Deserialize<object>(getString);
string name = item["name"];

//note: JavaScriptSerializer in this namespaces
//System.Web.Script.Serialization.JavaScriptSerializer

注意:也可以使用自定义对象。

Personel item = serializer.Deserialize<Personel>(getString);