I have an API JSON response that wraps the data content in a data property, which looks like this:
{
\"d
It's possible to get a User object using System.Text.Json API without specifying a name of property data from your JSON sample
{
"data":{
"email":"admin@example.com",
"mobile":"+1555555123",
"id":4,
"first_name":"Merchant",
"last_name":"Vendor",
"role":"Merchant",
}
}
by the following code
var document = JsonDocument.Parse(json, new JsonDocumentOptions { AllowTrailingCommas = true });
var enumerator = document.RootElement.EnumerateObject();
if (enumerator.MoveNext())
{
var userJson = enumerator.Current.Value.GetRawText();
var user = JsonSerializer.Deserialize(userJson,
new JsonSerializerOptions {AllowTrailingCommas = true});
}
In the sample above the JsonDocument is loaded, than RootElement is enumerated to get the first nested object as text to deserialize into User instance.
It's more easier to get a property by name like document.RootElement.GetProperty("data");, but the name can be different actually, according to your question. Accessing through indexer, like document.RootElement[0] is also not possible, because it works only when ValueKind of an element is Array, not the Object, like in your case
I've also changed the "id":4, to "id":"4",, because getting an error
Cannot get the value of a token type 'Number' as a string.