Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grabbing the value of a returned JSON string C#

I have JSON reply and i need to grab "Id" from it. I attempted 2 variations of the code below

    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'.

adjusted EnumerateObject to Enumerate Array but i still get the same error with 'Array' - 'Object' instead of 'Object' - 'Array'

the JSON reply has this format:

    {
    "code":1,
    "result":{
        "Id":1,
        "Name":"name"
        }
    }

I can't seem to be able to grab the specific Id using the bove method.

like image 230
enshadowed_ Avatar asked Oct 13 '25 09:10

enshadowed_


1 Answers

I think you're making this hard for yourself; it is much easier just to map to a type:

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;}
}

and use:

var root = JsonConvert.DeserializeObject<MyRoot>(json);
var result = root.Result;
// etc
like image 124
Marc Gravell Avatar answered Oct 14 '25 22:10

Marc Gravell