简体   繁体   English

C#Json.Net-如何反序列化包含其他对象数组的对象数组

[英]C# Json.Net - How to deserialize an array of objects containing an array of other objects

The Json data received from the http server is like this: 从http服务器接收的Json数据如下所示:

[
   {
      "token":"NlhYnzF0xqG"
   },
   [
      {
         "ts":"2019-03-21 14:06:22.123",
         "id":"CC_RTC_Second",
         "val":"22"
      },
      {
         "ts":"2019-03-21 14:06:00.096",
         "id":"CC_RTC_Minute",
         "val":"6"
      },
      {
         "ts":"2019-03-21 14:00:00.276",
         "id":"CC_RTC_Hour",
         "val":"14"
      }
   ]
]

I have tried some techniques presented in Newtonsoft.Json documentation, but I could not find the correct way. 我尝试了Newtonsoft.Json文档中介绍的一些技术,但是找不到正确的方法。 I spent two days by testing the solutions from StackOverflow answers, but with no success. 我花了两天时间测试来自StackOverflow答案的解决方案,但没有成功。

What C# types and techniques should I use in this particular case? 在这种特殊情况下,我应该使用哪些C#类型和技术?

Data structure can vary: 数据结构可能有所不同:
complete list of attributes is: td, id, val, flags, type, uts, nr. 属性的完整列表是:td,id,val,标志,类型,uts,nr。
All of them are strings. 它们都是字符串。
Server can omit the attrs if they do not exist, so for example I can obtain only ts + id. 服务器可以省略attrs(如果它们不存在),因此例如,我只能获得ts + id。
Is there any way how to work with such a data? 有什么办法可以处理这样的数据吗?

First of all your json is quite complicated and its tedious job to create a class hierarchy for your json, 首先,您的json非常复杂,并且为json创建类层次结构非常繁琐,

But one simple approach is that if you parse your JSON to JArray and then takes 但是一种简单的方法是,如果将JSON解析为JArray然后

  • 0th element to one class 0级元素到一类
  • And all remaining into list of another class 而所有剩余的进入另一个类的列表

Then might be you can retrieve all your json data 然后可能是您可以检索所有json数据

string json = File.ReadAllText(@"Path to your json");

JArray jArray = JArray.Parse(json);

Token token = jArray[0].ToObject<Token>();
jArray.RemoveAt(0);
RandomData[] tokenData = jArray.First.ToObject<RandomData[]>();

//--------------------Print Data to Console-------------------

Console.WriteLine(token.token + "\n");

foreach (var item in tokenData)
{
    Console.WriteLine("ts: " + item.ts);
    Console.WriteLine("id: " + item.id);
    Console.WriteLine("val: " + item.val + "\n");
}

Console.ReadLine();

And classes are, 班级是

class Token
{
    public string token { get; set; }
}

class RandomData
{
    public string ts { get; set; }
    public string td { get; set; }
    public string id { get; set; }
    public string val { get; set; }
    public string flags { get; set; }
    public string type { get; set; }
    public string uts { get; set; }
    public string nr { get; set; }
}

Output: 输出:

在此处输入图片说明

Note: You need to install NewtonSoft NuGet package and import using Newtonsoft.Json.Linq; 注意:您需要安装NewtonSoft NuGet软件包并using Newtonsoft.Json.Linq;导入using Newtonsoft.Json.Linq; namespace to your program. 程序的名称空间。

There is my version of answer: 有我的答案版本:

var strData = @"[{
         'token': 'NlhYnzF0xqG'
       },
       [{
         'ts': '2019-03-21 14:06:22.123',
         'id': 'CC_RTC_Second',
         'val': '22'
       }, {
         'ts': '2019-03-21 14:06:00.096',
         'id': 'CC_RTC_Minute',

       }, {

         'id': 'CC_RTC_Hour',
         'val': '14'
       }]
     ]";   
        var result = JsonConvert.DeserializeObject<List<JToken>>(strData);
        var tokens = result.Where( x=> x.Type == JTokenType.Object).Select(x=> x.ToObject<Token>());
        var innerData = result.Where(x => x.Type == JTokenType.Array).Select(x => x.ToObject<List<InnerData>>());

there are classes: 有课程:

 public class Token
        {
             public string token { set; get; }
        }
    public class InnerData
        {
            public string ts { set; get; }
            public string id { set; get; }
            public string val { set; get; }    
        }

You could print results as was mention before : 您可以如前所述打印结果:

foreach (var token in tokens)
{
    Console.WriteLine("ts: " + token.token);
}

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

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