C# 中来自 JSON 格式字符串(来自 REST API)的值

Values from JSON formatted string (from REST API) in C#

最近我接到一个约会,我需要使用它的 REST API 从云端下载一些数据,并将来自 "string" 的值存储在一个对象或一些变量中。下载完成,我现在需要做的就是以某种方式解析数据。

到目前为止,我编写了这种代码:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("some link");

request.ContentType = "application/json; charset=utf-8";
request.Method = "GET";
request.Headers.Add("Carriots.apiKey", "key");
using (WebResponse response = request.GetResponse())
{
    using(Stream stream = response.GetResponseStream())
    {
        StreamReader reader = new StreamReader(stream);
        JObject json = JObject.Parse(reader.ReadToEnd());
        Console.WriteLine(json.ToString());
    }
}

这是输出:

{
    "total_documents": 3,
    "result": [
    {
        "_id": "...",
        "protocol": "v1",
        "checksum": "",
        "_t": "str",
        "at": 1444134377,
        "device": "-just a device-",
        "data": {
            "field1": "123",
            "field2": "1536"
        },
        "id_developer": "....",
        "created_at": 1444134377,
        "owner": "-someUser-"
    }
    ]

}

我知道互联网上有很多解决方案,但其中 none 满足了我的需要。好的,我找到了一些东西,但是它在每一行上迭代并以这种方式检查值,但在我的情况下,我可以有数千个这样的输出。

是否有任何方法可以使用某种内置函数来完成所有这些(我的意思是解析),或者唯一的解决方案是迭代或编写一些正则表达式?

假设 json 将始终遵循此格式,请定义您的模型

public class jsonData{
    public int total_documents {get;set;}
    public resultData result {get;set;}
}

public class resultData{
    public int _id {get;set;}
    public string protocol {get;set;}
    ....
}

然后使用反序列化

Json.Deserialize<jsonData>(yourstring)