【问题标题】:Deserialize Complex Json in C# using Json.net使用 Json.net 在 C# 中反序列化复杂的 Json
【发布时间】:2017-08-25 20:32:36
【问题描述】:

我有一些复杂的 JSon,我试图将其解析为有意义的东西。我正在尝试使用 C# Json.net 反序列化,但我无法获得所需的值。我需要的是来自每个 ColData 节点的值,除了“摘要”部分中的值。我可以使用反序列化成一个对象,但我被困在那里。

    string pandltext = @"{
  "Header": {
    "Time": "2017-08-24T08:32:58-07:00",
    "ReportName": "ProfitAndLoss",
    "ReportBasis": "Accrual",
    "StartPeriod": "2017-06-01",
    "EndPeriod": "2017-06-30",
    "SummarizeColumnsBy": "Total",
    "Currency": "USD",
    "Option": [
      {
        "Name": "AccountingStandard",
        "Value": "GAAP"
      },
      {
        "Name": "NoReportData",
        "Value": "false"
      }
    ]
  },
  "Columns": {
    "Column": [
      {
        "ColTitle": "",
        "ColType": "Account",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "account"
          }
        ]
      },
      {
        "ColTitle": "Total",
        "ColType": "Money",
        "MetaData": [
          {
            "Name": "ColKey",
            "Value": "total"
          }
        ]
      }
    ]
  },
  "Rows": {
    "Row": [
      {
        "Header": {
          "ColData": [
            {
              "value": "Income"
            },
            {
              "value": ""
            }
          ]
        },
        "Rows": {
          "Row": [
            {
              "ColData": [
                {
                  "value": "Design income",
                  "id": "82"
                },
                {
                  "value": "975.00"
                }
              ],
              "type": "Data"
            },
            {
              "ColData": [
                {
                  "value": "Discounts given",
                  "id": "86"
                },
                {
                  "value": "-30.50"
                }
              ],
              "type": "Data"
            },
            {
              "Header": {
                "ColData": [
                  {
                    "value": "Landscaping Services",
                    "id": "45"
                  },
                  {
                    "value": "360.00"
                  }
                ]
              },
              "Rows": {
                "Row": [
                  {
                    "Header": {
                      "ColData": [
                        {
                          "value": "Job Materials",
                          "id": "46"
                        },
                        {
                          "value": ""
                        }
                      ]
                    },
                    "Rows": {
                      "Row": [
                        {
                          "ColData": [
                            {
                              "value": "Fountains and Garden Lighting",
                              "id": "48"
                            },
                            {
                              "value": "550.00"
                            }
                          ],
                          "type": "Data"
                        },
                        {
                          "ColData": [
                            {
                              "value": "Plants and Soil",
                              "id": "49"
                            },
                            {
                              "value": "1820.72"
                            }
                          ],
                          "type": "Data"
                        },
                        {
                          "ColData": [
                            {
                              "value": "Sprinklers and Drip Systems",
                              "id": "50"
                            },
                            {
                              "value": "30.00"
                            }
                          ],
                          "type": "Data"
                        }
                      ]
                    },
                    "Summary": {
                      "ColData": [
                        {
                          "value": "Total Job Materials"
                        },
                        {
                          "value": "2400.72"
                        }
                      ]
                    },
                    "type": "Section"
                  }
                ]
              },
              "Summary": {
                "ColData": [
                  {
                    "value": "Total Landscaping Services"
                  },
                  {
                    "value": "2760.72"
                  }
                ]
              },
              "type": "Section"
            },
            {
              "ColData": [
                {
                  "value": "Pest Control Services",
                  "id": "54"
                },
                {
                  "value": "-100.00"
                }
              ],
              "type": "Data"
            },
            {
              "ColData": [
                {
                  "value": "Sales of Product Income",
                  "id": "79"
                },
                {
                  "value": "44.00"
                }
              ],
              "type": "Data"
            },
            {
              "ColData": [
                {
                  "value": "Services",
                  "id": "1"
                },
                {
                  "value": "400.00"
                }
              ],
              "type": "Data"
            }
          ]
        },
        "Summary": {
          "ColData": [
            {
              "value": "Total Income"
            },
            {
              "value": "4049.22"
            }
          ]
        },
        "type": "Section",
        "group": "Income"
      },
      {
        "Summary": {
          "ColData": [
            {
              "value": "Gross Profit"
            },
            {
              "value": "4049.22"
            }
          ]
        },
        "type": "Section",
        "group": "GrossProfit"
      },
      {
        "Header": {
          "ColData": [
            {
              "value": "Expenses"
            },
            {
              "value": ""
            }
          ]
        },
        "Rows": {
          "Row": [
            {
              "Header": {
                "ColData": [
                  {
                    "value": "Automobile",
                    "id": "55"
                  },
                  {
                    "value": "19.99"
                  }
                ]
              },
              "Rows": {
                "Row": [
                  {
                    "ColData": [
                      {
                        "value": "Fuel",
                        "id": "56"
                      },
                      {
                        "value": "179.15"
                      }
                    ],
                    "type": "Data"
                  }
                ]
              },
              "Summary": {
                "ColData": [
                  {
                    "value": "Total Automobile"
                  },
                  {
                    "value": "199.14"
                  }
                ]
              },
              "type": "Section"
            },
            {
              "Header": {
                "ColData": [
                  {
                    "value": "Job Expenses",
                    "id": "58"
                  },
                  {
                    "value": "108.09"
                  }
                ]
              },
              "Rows": {
                "Row": [
                  {
                    "Header": {
                      "ColData": [
                        {
                          "value": "Job Materials",
                          "id": "63"
                        },
                        {
                          "value": ""
                        }
                      ]
                    },
                    "Rows": {
                      "Row": [
                        {
                          "ColData": [
                            {
                              "value": "Decks and Patios",
                              "id": "64"
                            },
                            {
                              "value": "88.09"
                            }
                          ],
                          "type": "Data"
                        }
                      ]
                    },
                    "Summary": {
                      "ColData": [
                        {
                          "value": "Total Job Materials"
                        },
                        {
                          "value": "88.09"
                        }
                      ]
                    },
                    "type": "Section"
                  }
                ]
              },
              "Summary": {
                "ColData": [
                  {
                    "value": "Total Job Expenses"
                  },
                  {
                    "value": "196.18"
                  }
                ]
              },
              "type": "Section"
            },
            {
              "Header": {
                "ColData": [
                  {
                    "value": "Legal & Professional Fees",
                    "id": "12"
                  },
                  {
                    "value": ""
                  }
                ]
              },
              "Rows": {
                "Row": [
                  {
                    "ColData": [
                      {
                        "value": "Accounting",
                        "id": "69"
                      },
                      {
                        "value": "75.00"
                      }
                    ],
                    "type": "Data"
                  },
                  {
                    "ColData": [
                      {
                        "value": "Lawyer",
                        "id": "71"
                      },
                      {
                        "value": "100.00"
                      }
                    ],
                    "type": "Data"
                  }
                ]
              },
              "Summary": {
                "ColData": [
                  {
                    "value": "Total Legal & Professional Fees"
                  },
                  {
                    "value": "175.00"
                  }
                ]
              },
              "type": "Section"
            },
            {
              "ColData": [
                {
                  "value": "Maintenance and Repair",
                  "id": "72"
                },
                {
                  "value": "185.00"
                }
              ],
              "type": "Data"
            },
            {
              "ColData": [
                {
                  "value": "Meals and Entertainment",
                  "id": "13"
                },
                {
                  "value": "5.66"
                }
              ],
              "type": "Data"
            },
            {
              "ColData": [
                {
                  "value": "Rent or Lease",
                  "id": "17"
                },
                {
                  "value": "900.00"
                }
              ],
              "type": "Data"
            },
            {
              "Header": {
                "ColData": [
                  {
                    "value": "Utilities",
                    "id": "24"
                  },
                  {
                    "value": ""
                  }
                ]
              },
              "Rows": {
                "Row": [
                  {
                    "ColData": [
                      {
                        "value": "Gas and Electric",
                        "id": "76"
                      },
                      {
                        "value": "114.09"
                      }
                    ],
                    "type": "Data"
                  },
                  {
                    "ColData": [
                      {
                        "value": "Telephone",
                        "id": "77"
                      },
                      {
                        "value": "74.36"
                      }
                    ],
                    "type": "Data"
                  }
                ]
              },
              "Summary": {
                "ColData": [
                  {
                    "value": "Total Utilities"
                  },
                  {
                    "value": "188.45"
                  }
                ]
              },
              "type": "Section"
            }
          ]
        },
        "Summary": {
          "ColData": [
            {
              "value": "Total Expenses"
            },
            {
              "value": "1849.43"
            }
          ]
        },
        "type": "Section",
        "group": "Expenses"
      },
      {
        "Summary": {
          "ColData": [
            {
              "value": "Net Operating Income"
            },
            {
              "value": "2199.79"
            }
          ]
        },
        "type": "Section",
        "group": "NetOperatingIncome"
      },
      {
        "Header": {
          "ColData": [
            {
              "value": "Other Expenses"
            },
            {
              "value": ""
            }
          ]
        },
        "Rows": {
          "Row": [
            {
              "ColData": [
                {
                  "value": "Miscellaneous",
                  "id": "14"
                },
                {
                  "value": "916.00"
                }
              ],
              "type": "Data"
            }
          ]
        },
        "Summary": {
          "ColData": [
            {
              "value": "Total Other Expenses"
            },
            {
              "value": "916.00"
            }
          ]
        },
        "type": "Section",
        "group": "OtherExpenses"
      },
      {
        "Summary": {
          "ColData": [
            {
              "value": "Net Other Income"
            },
            {
              "value": "-916.00"
            }
          ]
        },
        "type": "Section",
        "group": "NetOtherIncome"
      },
      {
        "Summary": {
          "ColData": [
            {
              "value": "Net Income"
            },
            {
              "value": "1283.79"
            }
          ]
        },
        "type": "Section",
        "group": "NetIncome"
      }
    ]
  }
}


// Deserialize to object
var rootObj = JsonConvert.DeserializeObject<ProfitLoss.Rootobject>( pandltext );

我尝试过查询 this post 中提到的 JContainer。我试过反序列化一个片段,如in the documentation 提到的,我试过使用文档中提到的here 的linq。到目前为止,我所有的努力都取得了不同程度的“成功”,但没有一个能够产生我想要获得的价值。最终,这些数据将绑定到 WPF DataGrid 以供查看。

编辑: 添加了整个 Json 文件

这些是获取一些东西的几次尝试,但在这两种情况下我都遇到了空值。

        // This always returns null
        var results2 = doc.Descendants()
                    .OfType<JObject>()
                    .Where( x => x[ "value" ] != null );


        // This gives me a null exception error 
        var doc1 = ( JContainer ) o[ "Rows" ];
        foreach ( var row in rootObj.Rows.Row )
        {
                // Get a null exception
                foreach ( var row2 in row.Rows.Row )
                {
                    Console.WriteLine( row2.ToString() );
                }

        }

编辑 2: 使用@Eser 给出的内容作为起点,我可以获得一个值列表,但不幸的是它只是一个值列表。而不是得到类似的东西

"Design income", "975.00"
"Discounts given", "-30.50"

我明白了

"Design income"
"975"
"Discounts given"
"-30.50"

这是我用来获取值列表的代码:

var jObj = JObject.Parse( pandltext );
var results = jObj.SelectTokens( "$..Rows.Row[?(@.type == 'Data')]..value" ).ToList();

【问题讨论】:

  • 请用代码发布一些您尝试过的示例,并描述它如何无法按预期工作。
  • 另外,发布一个有效/完整的 json,以便人们可以使用它。
  • 你为什么不尝试使用正则表达式?
  • @Youssef13 您可以反序列化为对象,然后使用 Linq。你为什么要为此使用正则表达式。
  • @Youssef13 使用适当的工具。正则表达式在这里不是合适的工具。

标签: c# .net json json.net deserialization


【解决方案1】:
var jObj = JObject.Parse(json);

var colData = jObj.SelectTokens("$..ColData")
                .Except(jObj.SelectTokens("$..Summary.ColData"))
                .ToList();

编辑

foreach(var item in colData)
{
    Console.WriteLine(string.Join("=", item.Select(x => x["value"])));
}

var finalList = colData.Select(item => item.Select(x => (string)x["value"]).ToList())
               .ToList();

【讨论】:

  • 谢谢@Eser。我以此为起点来获取值列表,但我仍在努力使其可用。使用您答案中的代码,我得到一个类似于 {[ { "value": "Design income", "id": "82" }, { "value": "975.00" } ]} 的值,但我无法访问列表中的值。我需要“设计收入”和“975.00”。
  • @mack 将答案中棘手的部分放入您的问题中,并用您新的无能来扩展您的问题。这是提问的方式吗?无论如何,我已经彻底更新了答案。
  • 感谢您抽出宝贵时间回答这个问题。我不打算用我的编辑来改变问题,只是在原始问题中添加新信息。对不起,如果这改变了原来的问题。再次感谢您的帮助。你的回答让我再次朝着正确的方向前进。
【解决方案2】:
    public class Option
    {
         public string Name { get; set; }
         public string Value { get; set; }
    }

    public class Header
    {
        public DateTime Time { get; set; }
        public string ReportName { get; set; }
        public string ReportBasis { get; set; }
        public string StartPeriod { get; set; }
        public string EndPeriod { get; set; }
        public string SummarizeColumnsBy { get; set; }
        public string Currency { get; set; }
        public IList<Option> Option { get; set; }
    }

    public class MetaData
    {
        public string Name { get; set; }
        public string Value { get; set; }
    }

    public class Column
    {
        public string ColTitle { get; set; }
        public string ColType { get; set; }
        public IList<MetaData> MetaData { get; set; }
    }

    public class Columns
    {
        public IList<Column> Column { get; set; }
    }

    public class ColData
    {
         public string value { get; set; }
         public string id { get; set; }
    }

    public class ColData
    {
         public string value { get; set; }
         public string id { get; set; }
    }

    public class Row
    {
        public IList<ColData> ColData { get; set; }
        public string type { get; set; }
    }

    public class Rows
    {
        public IList<Row> Row { get; set; }
    }

    public class ColData
    {
        public string value { get; set; }
    }

    public class Summary
    {
        public IList<ColData> ColData { get; set; }
    }

    public class ColData
    {
        public string value { get; set; }
        public string id { get; set; }
    }

    public class Row
    {
        public  Header { get; set; }
        public Rows Rows { get; set; }
        public Summary Summary { get; set; }
        public string type { get; set; }
        public IList<ColData> ColData { get; set; }
    }

    public class Rows
    {
        public IList<Row> Row { get; set; }
    }

    public class Row
    {
        public IList<ColData> ColData { get; set; }
        public string type { get; set; }
        public  Header { get; set; }
        public Rows Rows { get; set; }
        public  Summary { get; set; }
    }

    public class Rows
    {
        public IList<Row> Row { get; set; }
    }

    public class Row
    {
        public  Header { get; set; }
        public Rows Rows { get; set; }
        public  Summary { get; set; }
        public string type { get; set; }
        public string group { get; set; }
    }

    public class Rows
    {
        public IList<Row> Row { get; set; }
    }

    public class Example
    {
        public Header Header { get; set; }
        public Columns Columns { get; set; }
        public Rows Rows { get; set; }
    }

并将其与 :

一起使用
Example results =  Newtonsoft.JSON.JsonConvert.DeserializeObject<Example>(json);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-01
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多