【问题标题】:How to get value from JSON Dictionary using Newtonsoft.Json如何使用 Newtonsoft.Json 从 JSON 字典中获取价值
【发布时间】:2014-10-14 05:43:33
【问题描述】:

我是 json 新手,这里有个小问题无法解决。

在其他 json 中,我有 {"certificate":"123456789",},我得到了使用的价值。

model.cs

class Login //this code is working.
{
    [JsonProperty("certificate")]
    public string certificate { get; set; }
}

但我的问题是,当我想出 json 字典时,我不知道如何从中获取价值。

这是我来自 controller.cs 的代码,用于从 Saba/api/component/location 获取 json

using(var client = new HttpClient()) //I'm sure this code is working.
        {
            client.BaseAddress = new Uri(string.Format("https://{0}/", HostUrl));
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("SabaCertificate", certificate);
            //HTTP GET: /Saba/api/componet/location
            HttpResponseMessage response = await client.GetAsync("Saba/api/component/location");
            if(response.IsSuccessStatusCode)
            {

                Location saba = await response.Content.ReadAsAsync<Location>();
                //I always get empty location when I try to run the app.
            }
        }

这是带有字典的 JSON。

{
"results": [
    {
        "loc_name": "Aberdeen - Aberdeen Town Square_489",
        "id": "locat000000000001877",
        "href": "https://na1.sabacloud.com/Saba/api/component/location/locat000000000001877"
    }]

}

如何获取json字典的值?

我试过的是

模型.cs

[JsonProperty("results")] \\ AggregateException Error
class Location
{
    [JsonProperty("loc_name")]
    public string loc_name { get; set; }

    [JsonProperty("id")]
    public string id { get; set; }

    [JsonProperty("href")]
    public string href { get; set; }
}

但我无法检索该值。

【问题讨论】:

  • 您的 JSON 无效。你有一个开场 [,但没有闭场 ]
  • @Chips_100 完成编辑:D
  • “它不工作”(我假设你的意思是这样)没有提供关于它如何它不工作的信息。此外,您还没有向我们展示哪些代码不起作用 - 您已经发布了您的课程,但没有说明您如何尝试转换 JSON。请发布一个简短但完整的程序来演示问题,包括预期行为和实际行为的明确行为。

标签: c# json dictionary json.net


【解决方案1】:

根据您问题中发布的 JSON,您应该有类似

public class Result
{
    public string loc_name { get; set; }
    public string id { get; set; }
    public string href { get; set; }
}

public class RootObject
{
    public List<Result> results { get; set; }
}

然后打电话

var rootObject = JsonConvert.DeserializeObject<RootObject>(jsonData);

您始终可以使用 JSON Formatter & Validator 来测试您的 JSON 是否有效,并使用 json2csharp 从 json 生成 c# 类。

【讨论】:

    猜你喜欢
    • 2016-05-09
    • 1970-01-01
    • 2018-07-08
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    相关资源
    最近更新 更多