【问题标题】:How to parse double list JSON data in c#如何在 C# 中解析双列表 JSON 数据
【发布时间】:2015-04-10 07:11:22
【问题描述】:

我通过调用格式如下的服务获取 JSON 数据:

[
  [
    {
      "AgentStatus": "- Active",
      "Basement": "None",
      "BasementType": "",
      "Baths": "4",
      "BathsHalf": "1",
      "Beds": "6"
    },
    [
      "372010-1.jpg"
    ]
  ],
  [
    {
      "AgentStatus": "- Active",
      "Basement": "Finished,Full",
      "BasementType": "FULL FINISHED",
      "Baths": "2",
      "BathsHalf": "1",
      "Beds": "3"
    },
    [
      "377388-1.jpg",
      "377388-2.jpg",
      "377388-12.jpg"
    ]
  ]
]

为了解析这个 JSON,我制作了这样的类:

public class RetsProperty
{
    public PropertyAttributes PropAttributes { get; set; }

    public string[] ImgUrls { get; set; }
}

public class PropertyAttributes
{
    public string AgentStatus { get; set; }

    public string Basement { get; set; }

    public string BasementType { get; set; }

    public string Baths { get; set; }

    public string BathsHalf { get; set; }

    public string Beds { get; set; }
}

我已经使用 Newtonsoft Json 反序列化 JSON 数据

var retsPropertyItems = Newtonsoft.Json.JsonConvert.DeserializeObject<List<RetsProperty>>(propertyJsonString);

但它无法解析它返回以下错误:

我认为是因为我无法正确创建类。

那么我该如何格式化我的课程呢? 还是可以像我一样绘制地图?

谢谢

【问题讨论】:

  • 这个 json 是否应该是 RetsProperty 的列表?,json 对我来说似乎格式不正确(看起来是提供一个二维对象数组)
  • 您可以访问 JSON 吗?将内部数组更改为对象
  • 不,我没有任何访问权限。我从服务电话中得到它。
  • 您可能会遇到困难,然后基本上您有一个带有PropertyAttributes 对象和字符串数组的二维数组,每个数组中有一个对象([ [ PropertyAttributes, [strings] ], [ PropertyAttributes, [strings] ] ]),它可能仍然可行,只是不行就像获取RetsProperty的单个列表一样简单

标签: c# json asp.net-mvc web-services


【解决方案1】:

您的 JSON 格式真的很糟糕,因为它在数组中包含没有属性名称的数组。所以你应该仔细解析它。

我想出了一个解决方案,它可能不是那么糟糕且易于理解(如果我理解你的 JSON 格式正确)。这个想法是用属性名称包装你的 JSON,然后解析他的构造。

您应该以同样的方式包装您的 JSON

var wrappedText = @"{ ""Prop"": " + propertyJsonString + " }";

然后你可以用 Newtonsoft Json 解析:

var jsonData = JObject.Parse(wrappedText);

现在您有了 JSON 数据,您应该手动解析它。我建议你这样:

List<RetsProperty> RetsProperties = new List<RetsProperty>();
foreach (var prop in jsonData["Prop"])
{
    RetsProperties.Add(new RetsProperty
        {
            ImgUrls = Newtonsoft.Json.JsonConvert.DeserializeObject<string[]>(prop.Last.ToString()),
            PropAttributes = Newtonsoft.Json.JsonConvert.DeserializeObject<PropertyAttributes>(prop.First.ToString())
        });
};

您应该了解,i只有在最后一个数组中有 2 个数组项时才会起作用。看看prop.Firstprop.Last

【讨论】:

    【解决方案2】:

    首先,您有一个非常奇怪的 JSON,但正如您所说,您是从外部服务收到的。你可以使用JArrayLINQ解析这样的JSON,当然这种方法非常依赖JSON的结构。

    var retsProperties = JArray.Parse(json)
        .Select(item => new RetsProperty
        {
            PropAttributes = item.First.ToObject<PropertyAttributes>(),
            ImgUrls = item.Last.ToObject<string[]>()
        })
        .ToList();
    

    【讨论】:

      猜你喜欢
      • 2016-10-15
      • 1970-01-01
      • 1970-01-01
      • 2020-07-11
      • 2014-09-05
      • 1970-01-01
      • 2019-06-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多