【问题标题】:Retrieve the information from a nested JSON value从嵌套的 JSON 值中检索信息
【发布时间】:2016-10-28 08:24:15
【问题描述】:

所以我调用 LinkedIn API 来获取个人资料数据并检索 JSON。

{
  "firstName": "Cristian Viorel",
  "headline": ".NET Developer",
  "location": {
    "country": {"code": "dk"},
    "name": "Northern Region, Denmark"
  },
  "pictureUrls": {
    "_total": 1,
    "values": ["https://media.licdn.com/mpr/mprx/0_PXALDpO4eCHpt5z..."]
  }
}

我可以使用 student.firstname、student.headline。如何获取位置的名称或 pictureUrl 的值? 像 student.location.name 或 student.pictureUrls.values 之类的东西?

【问题讨论】:

  • 你的建议试过了吗?

标签: c# json parsing


【解决方案1】:

Json.Net 非常简单。你首先定义你的模型:

public class Country
{
    public string code { get; set; }
}

public class Location
{
    public Country country { get; set; }
    public string name { get; set; }
}

public class PictureUrls
{
    public int _total { get; set; }
    public List<string> values { get; set; }
}

public class JsonResult
{
    public string firstName { get; set; }
    public string headline { get; set; }
    public Location location { get; set; }
    public PictureUrls pictureUrls { get; set; }
}

然后你只需解析你的 Json 数据:

string json = @"{
      'firstName': 'Cristian Viorel',
      'headline': '.NET Developer',
      'location': {
        'country': {'code': 'dk'},
        'name': 'Northern Region, Denmark'
      },
      'pictureUrls': {
        '_total': 1,
        'values': ['https://media.licdn.com/mpr/mprx/0_PXALDpO4eCHpt5z...']
      }
    }";

JsonResult result = JsonConvert.DeserializeObject<JsonResult>(json);

Console.WriteLine(result.location.name);

foreach (var pictureUrl in result.pictureUrls.values)
    Console.WriteLine(pictureUrl);

【讨论】:

    【解决方案2】:

    对于名称是的,但是对于图片,您需要一个 for 循环,或者如果您只想要第一项 student.pictureUrls.values[0](值似乎是一个数组)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-11
      • 1970-01-01
      相关资源
      最近更新 更多