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

ens*_*ed_ 3 c# serialization json

我有 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());
               }
         }
   }
Run Code Online (Sandbox Code Playgroud)

请求的操作需要类型为“Object”的元素,但目标元素的类型为“Number”。

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

JSON 回复具有以下格式:

    {
    "code":1,
    "result":{
        "Id":1,
        "Name":"name"
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ell 7

我认为你在为自己做这件事;它是容易只是映射到一个类型:

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;}
}
Run Code Online (Sandbox Code Playgroud)

并使用:

var root = JsonConvert.DeserializeObject<MyRoot>(json);
var result = root.Result;
// etc
Run Code Online (Sandbox Code Playgroud)