JSON.net 筛选从网站收到的存储库

JSON.net filter repositories received from website

你好 Whosebug 社区, 我最近接触了 C# 和 JSON.net,我的任务是过滤我从网站收到的存储库。我正在使用 Crucible API.

client.Authenticator = new HttpBasicAuthenticator(User, Password);
var request = new RestRequest("", Method.GET);
Console.Clear();

client.ExecuteAsync(request, response => {
    Console.WriteLine(response.Content);
});

Console.Read();

除了我在控制台应用程序中收到的存储库的显示名称之外,我如何过滤掉所有内容?当前输出如下所示:

{
    "repoData": [{
            "name": "Example",
            "displayName": "Example",
            "type": "git",
            "enabled": true,
            "available": true,
            "location": "Example.com",
            "path": ""
        }
    ]
}

您可以使用 JsonConvert.DeserializeObject。例子如下

https://www.newtonsoft.com/json/help/html/DeserializeObject.htm

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

顺便说一下,您的 JSON 不完整。请添加完整的输出,以便其他人可以提供更好的帮助。

为您的json

创建一个快速类型
public class RepoData
{
    public string name { get; set; }
    public string displayName { get; set; }
    public string type { get; set; }
    public bool enabled { get; set; }
    public bool available { get; set; }
    public string location { get; set; }
    public string path { get; set; }
}

public class RootObject4
{
    public List<RepoData> repoData { get; set; }
}

这里我创建了一个控制台应用程序用于演示目的

class Program
{
    static void Main(string[] args)
    {
        var json = @"{'repoData':[{'name':'Example','displayName':'Example1','type':'git','enabled':true,'available':true,'location':'Example.com','path':''}, {'name':'Example','displayName':'Example2','type':'git','enabled':true,'available':true,'location':'Example.com','path':''}]}";

        RootObject4 rootObject4 = JsonConvert.DeserializeObject<RootObject4>(json);

        List<string> displayNames = new List<string>();

        foreach (var item in rootObject4.repoData)
        {
            displayNames.Add(item.displayName);
        }

        displayNames.ForEach(x => Console.WriteLine(x));

        Console.ReadLine();
    }
}

备选方案: 如果您不想创建任何 类,那么 JObject 将更好地处理您的 json,您将提取displayName 以下代码示例控制台应用程序的值。

class Program
{
    static void Main(string[] args)
    {
        var json = @"{'repoData':[{'name':'Example','displayName':'Example1','type':'git','enabled':true,'available':true,'location':'Example.com','path':''}, {'name':'Example','displayName':'Example2','type':'git','enabled':true,'available':true,'location':'Example.com','path':''}]}";

        JObject jObject = JObject.Parse(json);

        var repoData = jObject["repoData"];

        var displayNames = repoData.Select(x => x["displayName"]).Values().ToList();

        displayNames.ForEach(x => Console.WriteLine(x));

        Console.ReadLine();
    }
}

输出: