【问题标题】:c# newtonsoft parse inner arraysc# newtonsoft 解析内部数组
【发布时间】:2016-09-15 01:21:40
【问题描述】:

我将我的 json 反序列化为一个模型类,但我想在保存到 sqlite 之前对 box 数组做一些工作,我被困在循环遍历所有盒子并获取值。

{
"data": [ // single outer array
    {
        "id": 8620379, 
        "business_id": 191, 
        "business_name": "yada", 
        "boxes": [
            {
                "box_id": 485, 
                "box_name": "5/6", 
                "box_group": null
            }, 
            {
                "box_id": 483, 
                "box_name": "1/2", 
                "box_group": null
            }, 
            {
                "box_id": 484, 
                "box_name": "3/4", 
                "box_group": null
            }
        ]
    }, 
    {
        "id": 8636759, 
        "business_id": 257, 
        "business_name": "something else", 
        "boxes": [
            {
                "box_id": 1176, 
                "box_name": "FC", 
                "box_group": null
            }
        ]
    }, // and more boxes

【问题讨论】:

标签: c# json c#-4.0


【解决方案1】:
  1. 为 JSON 对象创建一个模型。 (http://json2csharp.com/)
public class Box
{
    public int box_id { get; set; }
    public string box_name { get; set; }
    public object box_group { get; set; }
}

public class Datum
{
    public int id { get; set; }
    public int business_id { get; set; }
    public string business_name { get; set; }
    public List<Box> boxes { get; set; }
}

public class RootObject
{
    public List<Datum> data { get; set; }
}
  1. 使用 Json.NET JSON 反序列化器,
RootObject obj = JsonConvert.DeserializeObject<RootObject>("your json string"); 

【讨论】:

  • 是的,我这样做了,但是 sqlite 不能使用 List 框,我需要遍历所有框并将基准 ID 与其他字段一起插入到框表中,所以对于每个基准ID选择所有框,添加基准ID并执行sql插入
  • 尝试使用 List.ToArray() 方法将列表转换为数组。然后使用 foreach 循环迭代集合...
猜你喜欢
  • 2014-08-14
  • 1970-01-01
  • 2022-11-17
  • 2016-06-16
  • 1970-01-01
  • 2017-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多