牛顿软件 JSON 反序列化

我的 JSON 如下:

{"t":"1339886","a":true,"data":[],"Type":[['Ants','Biz','Tro']]}

我发现了用于 C # 的 Newtonsoft JSON.NET 反序列化库:

object JsonDe = JsonConvert.DeserializeObject(Json);

如何访问 JsonDe对象以获得所有的“类型”数据?我用一个循环试了一下,但是它不起作用,因为对象没有枚举器。

287035 次浏览

You can implement a class that holds the fields you have in your JSON

class MyData
{
public string t;
public bool a;
public object[] data;
public string[][] type;
}

and then use the generic version of DeserializeObject:

MyData tmp = JsonConvert.DeserializeObject<MyData>(json);
foreach (string typeStr in tmp.type[0])
{
// Do something with typeStr
}

Documentation: Serializing and Deserializing JSON

A much easier solution: Using a dynamic type

As of Json.NET 4.0 Release 1, there is native dynamic support. You don't need to declare a class, just use dynamic :

dynamic jsonDe = JsonConvert.DeserializeObject(json);

All the fields will be available:

foreach (string typeStr in jsonDe.Type[0])
{
// Do something with typeStr
}


string t = jsonDe.t;
bool a = jsonDe.a;
object[] data = jsonDe.data;
string[][] type = jsonDe.Type;

With dynamic you don't need to create a specific class to hold your data.

As per the Newtonsoft Documentation you can also deserialize to an anonymous object like this:

var definition = new { Name = "" };


string json1 = @"{'Name':'James'}";
var customer1 = JsonConvert.DeserializeAnonymousType(json1, definition);


Console.WriteLine(customer1.Name);
// James
//Your snippet
object JsonDe = JsonConvert.DeserializeObject(Json);


//what you need to do
JObject JsonDe = JsonConvert.DeserializeObject<JObject>(Json);

Now you have and object with suitable properties and methods to work with the data.

You could also use Dictionary<string,object> instead of JObject. However, there are other alternatives, strongly-type though.

NewtonSoft.Json is an excellent library. I have used it for many use cases.

The beauty of json is that one can create schemas dynamically. Therefore we need to be able to write generic code to work with them