在c#中反序列化Json对象

时间:2017-07-15 03:38:03

标签: c# json json-deserialization

我有从另一个应用程序返回的json对象,我无法控制它并且每个对象的结构不同,但我想从每个对象中提取相同的数据及其标题(我正在使用NewtownSoft):< / p>

{
"myData": [
{
  "one": {
    "in": 0,
    "out": 17,
    "total": 17
  },
  "two": {
    "total": 17
  },
  "three": {
    "total": 0
  },
  "four": {
    "total": 8
  },
  "five": {
    "total": 0
  },
  "six": {
    "total": 0
  },
  "seven": {
    "total": 0
  }
}  ]}

我希望结果与此图像一样

enter image description here

并仅使用一个类

反序列化此代码
public class Example{
public string number {get;set;}
public int total {get; set;}
}

1 个答案:

答案 0 :(得分:0)

如果您可以控制生成的JSON,请修改JSON:

{
"myData": [
{
  "Example": {
    "number": "one",
    "in": 0,
    "out": 17,
    "total": 17
  },
  "Example": {
    "number": "two",
    "total": 17
  },
  "Example": {
    "number": "three",
    "total": 0
  },
  "Example": {
    "number": "four",
    "total": 8
  },
  "Example": {
    "number": "five",
    "total": 0
  },
  "Example": {
    "number": "six",
    "total": 0
  },
  "Example": {
    "number": "seven",
    "total": 0
  }
}  ]}

C#Classes:

public class Example
{
    public string number { get; set; }
    public int total { get; set; }
}

public class MyData
{
    public Example Example { get; set; }
}

public class RootObject
{
    public List<MyData> myData { get; set; }
}