enshadowed_
enshadowed_

Reputation: 109

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.

Upvotes: 4

Views: 10741

Answers (2)

Pavel Anikhouski
Pavel Anikhouski

Reputation: 23228

You can enumerate the parsed JsonDocument Root element and result element. Or do it recursively for every child node that has JsonValueKind.Object type and get the id value

using (var document = JsonDocument.Parse(File.ReadAllText("test.json")))
{
    JsonElement root = document.RootElement;
    var names = new List<string>();
    Enumerate(root);

    void Enumerate(JsonElement element)
    {
        if (element.ValueKind == JsonValueKind.Object)
        {
            foreach (var item in element.EnumerateObject())
            {
                if (item.Value.ValueKind == JsonValueKind.Object)
                {
                    Enumerate(item.Value);
                }

                if (item.Value.ValueKind == JsonValueKind.Number && item.Name == "Id")
                {
                    //Console.WriteLine(item.Value.GetRawText());
                    names.Add(item.Value.GetRawText());
                }
            }
        }
    }
}

This code allows you to enumerate JSON with any number of nesting levels

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1062865

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

Upvotes: 8

Related Questions