简体   繁体   English

如何反序列化JSON对象?

[英]How to deserialize JSON-Object?

i am trying to deserialize a JSON-Object which looks quite similiar to an Array. 我试图反序列化一个看起来像一个数组的JSON对象。 Here's the JSON-String: 这是JSON-String:

...,"Test":[[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14]],...

I do not want to deserialize it as 2D Array, because each of these values have an explicit meaning to me. 我不想将其反序列化为2D数组,因为这些值中的每一个对我都有明确的含义。 I would like to access it like this: 我想这样访问它:

Test[0].Example (0)
Test[0].Êxample2 (1)
Test[0].Example3 (2)
...
Test[2].Example (10)

I hope you got the idea and have a solution to my Problem. 希望您有主意,并能解决我的问题。

I am using the Newtonsoft JSON Library together with C#. 我正在将Newtonsoft JSON库与C#一起使用。

EDIT1: Maybe i should be more specific of how deserilisation is done until now: EDIT1:也许到目前为止,我应该更详细地说明如何进行反消毒:

JSON: "Object":{"A":0,"Test":[[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14]],"B":1,...} JSON: "Object":{"A":0,"Test":[[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14]],"B":1,...}

C#: C#:

m_Object = JsonConvert.DeserializeObject<Object>(jsonString);

The Class Object is defined in C# containing all the fields of the JSON-String. C#中定义了Class对象,其中包含JSON-String的所有字段。

Object-Class: 对象的类:

class Object
{
public Int32 A {get;set;}

public Object Test {get;set;}

public Int32 B {get;set;}
}

You can use LINQ to JSON: 您可以使用LINQ转JSON:

string json = "[[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14]]";

var tests = JsonConvert.DeserializeObject<JArray>(json)
    .Cast<JArray>()
    .Select(a => new Test { 
         Example = (int)a[0],
         Example2 = (int)a[1]
         // etc
    });

Result: 结果:

在此处输入图片说明

UPDATE: For your updated question - you can deserialize json object, and then access its properties by their keys 更新:对于您的更新问题-您可以反序列化json对象,然后通过其键访问其属性

string json = @"{'A':0,'Test':[[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14]],'B':1}";

var obj = JsonConvert.DeserializeObject<JObject>(json);
var test = (JArray)obj["Test"];
var result = new {
    A = (int)obj["A"],
    B = (int)obj["B"],
    Test = test.Cast<JArray>().Select(a => new Test {
        Example = (int)a[0],
        Example2 = (int)a[1],
        Example3 = (int)a[2],
        Example4 = (int)a[3],
        Example5 = (int)a[4]
    })
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM