【问题标题】:Get a specific value from a json structure从 json 结构中获取特定值
【发布时间】:2021-08-11 17:42:24
【问题描述】:

我有这个 json:

{
    "unashamedohio": 
        {
            "id": 107537,
            "name": "UnashamedOhio",
            "profileIconId": 785,
            "revisionDate": 1439997758000,
            "summonerLevel": 30
        }
}

我想获取名为summonerLevel的字段。

我试过把这个json转成字符串然后搜索summonerLevel,但是我知道这个解决方案不行。

我正在使用 Json.NET。

【问题讨论】:

  • 在 Stack Overflow 上有 很多 的关于解析 JSON 的问题。您可以将其解析为您事先创建了适当类的对象,或使用 Json.NET 的“LINQ to JSON”或任何数量的东西。请展示你到目前为止所做的尝试。
  • 可以在字符串中搜索。另一种选择可能是仅使用您关心的数据反序列化到另一个对象,但这也不是一个好主意。是否有任何理由不能将 JSON 反序列化为整个对象,然后只检查对象上的值?

标签: c# json json.net


【解决方案1】:

您可以使用dynamic 关键字

dynamic obj = JsonConvert.DeserializeObject(json);
Console.WriteLine(obj.unashamedohio.summonerLevel);

【讨论】:

  • 谢谢,这个工作还不错。可能需要阅读有关动态对象的更多信息。感谢所有顺便说一句
  • 我真的很喜欢动态,在某些情况下使用它是唯一的解决方案,但 IMO 应该谨慎使用它。
【解决方案2】:

我假设这个 json 存储在一个字符串中,假设称为 json...所以试试

string json = "...";
JObject obj = JsonConvert.DeserializeObject<JObject>(json);
JObject innerObj = obj["unashamedohio"] as JObject;
int lolSummorLvl = (int) innerObj["summonerLevel"];

【讨论】:

  • 无法将类型 'System.Collections.Generic.Dictionary' 隐式转换为 'Newtonsoft.Json.Linq.JObject'2013\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs。这就是我在 Jobject obj 行中遇到的错误
  • 听起来您的 json 存储在字典中,而不是字符串中。
【解决方案3】:

您有几种可能性(如其他答案中所示)。另一种可能性是使用 Json.Net 提供的 JObjectJProperty 属性,以便直接获取如下值:

var jsonObject = (JObject)JsonConvert.DeserializeObject(json);
var unashamedohio = (JObject)(jsonObject.Property("unashamedohio").Value);
var summonerLevel = unashamedohio.Property("summonerLevel");
Console.WriteLine(summonerLevel.Value);

另一种可能性是创建 JSON 结构的类型化模型:

public class AnonymousClass
{
    public UnashamedOhio unashamedohio { get; set; }    
}

public class UnashamedOhio
{
    public int summonerLevel { get; set; }
}

并使用它来检索值:

var ao = JsonConvert.DeserializeObject<AnonymousClass>(json);
Console.WriteLine(ao.unashamedohio.summonerLevel);

两种解决方案都打印相同的值:30

IMO 您应该尽可能使用始终类型化的模型,并且如果您从 JSON 结构中获取大量值。它在 IDE 中提供错误检查(而不是动态检查),这在运行时得到回报。

【讨论】:

    【解决方案4】:

    这对我有用

    在这里找到 - How do you read a simple value out of some json using System.Text.Json?

    var jsonResult = JsonSerializer.Deserialize<JsonElement>(apiResponse).GetProperty("collection");
                            return jsonResult.EnumerateArray();
    

    带有 HTTPCLient GET 的代码:

                using (var httpClient = new HttpClient())
                {
                    // Headers
                    httpClient.DefaultRequestHeaders.Add("X-AppSecretToken", "sJkvd4hgr45hhkidf");
                    httpClient.DefaultRequestHeaders.Add("X-AgreementGrantToken", "r55yhhsJkved4ygrg5hssdhkidf");
    
                    using (var response = await httpClient.GetAsync("https://restapi/customers"))
                    {
                        string apiResponse = await response.Content.ReadAsStringAsync(); // Result
    
                        var jsonResult = JsonSerializer.Deserialize<JsonElement>(apiResponse).GetProperty("collection");
                        return jsonResult.EnumerateArray();
                     
                    }
                }
    

    【讨论】:

      猜你喜欢
      • 2015-04-23
      • 2021-11-15
      • 1970-01-01
      • 1970-01-01
      • 2019-03-30
      • 2017-11-22
      • 2017-09-19
      • 2023-03-04
      • 1970-01-01
      相关资源
      最近更新 更多