gpt4 book ai didi

c# - 获取返回的 JSON 字符串 C# 的值

转载 作者:行者123 更新时间:2023-12-04 00:01:26 25 4
gpt4 key购买 nike

我有 JSON 回复,我需要从中获取“Id”。我尝试了以下代码的 2 个变体

    using (JsonDocument document = JsonDocument.Parse(jsonstring))
{

JsonElement root = document.RootElement;
JsonElement resultsElement = root.GetProperty("Result");
List<string> names = new List<string>();

foreach (var result in resultsElement.EnumerateObject())
{


if (result.Value.TryGetProperty("Id", out resultsElement))
{
names.Add(resultsElement.GetString());
}
}
}

The requested operation requires an element of type 'Object', but the target element has type 'Number'.



将 EnumerateObject 调整为 Enumerate Array 但我仍然遇到相同的错误,使用 'Array' - 'Object' 而不是 'Object' - 'Array'

JSON 回复具有以下格式:
    {
"code":1,
"result":{
"Id":1,
"Name":"name"
}
}

我似乎无法使用 bove 方法获取特定的 Id。

最佳答案

我认为你在为自己做这件事;仅映射到类型要容易得多:

public class MyRoot {
[JsonProperty("code")]
public int Code {get;set;}
[JsonProperty("result")]
public MyResult Result {get;set;}
}
public class MyResult {
public int Id {get;set;}
public string Name {get;set;}
}

并使用:

var root = JsonConvert.DeserializeObject<MyRoot>(json);
var result = root.Result;
// etc

关于c# - 获取返回的 JSON 字符串 C# 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60636632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com