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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With