【问题标题】:How to parse the array of JSON using C#如何使用 C# 解析 JSON 数组
【发布时间】:2016-10-04 09:13:40
【问题描述】:

我需要使用 C# 解析作为数组集合的 JSON 数据。

ItemRelations: [
    {
        rel: "System.Links.H-Forward",
        source: {id: 123456,url: "https://somename.domain.com/DefaultCollection/_apis/wit/Items/123456"},
        target: {id: 231856,url: "https://somename.domain.com/DefaultCollection/_apis/wit/Items/231856"}
    }
]

我可以解析简单的 JSON 字符串,但是当遇到上述情况时,我应该如何进行?

【问题讨论】:

  • 请参考stackoverflow.com/questions/15726197/…link。它可能对你有帮助
  • 搜索 Newtonsoft.Json 并阅读一些文档。它真的很强大,你可能甚至不需要做太多事情。 Visual Studio 也有一个功能 Edit->Paste Special -> Paste JSON as Classes。
  • 看看newtonsoft.com/json。这可能会有所帮助
  • 您粘贴的 JSON 不是简单的对象或数组,而是对象数组。希望对您有所帮助。
  • 发布的文字不是合法的json,具体的key需要用引号括起来。

标签: c# json


【解决方案1】:

您可以使用Json2csharp 为您的 json 生成类。然后使用来自 nuget 的 Json.Net:

void Main()
{
    var json = @"{ItemRelations: [
    {
        rel: ""System.Links.H-Forward"",
        source: {id: 123456,url: ""https://somename.domain.com/DefaultCollection/_apis/wit/Items/123456""},
        target: {id: 231856,url: ""https://somename.domain.com/DefaultCollection/_apis/wit/Items/231856""}
    }
]}";

    var parsed = JsonConvert.DeserializeObject<RootObject>(json);

    //Linqpad
    //parsed.Dump();
}

public class Source
{
    public int id { get; set; }
    public string url { get; set; }
}

public class Target
{
    public int id { get; set; }
    public string url { get; set; }
}

public class ItemRelation
{
    public string rel { get; set; }
    public Source source { get; set; }
    public Target target { get; set; }
}

public class RootObject
{
    public List<ItemRelation> ItemRelations { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多