System.Text.Json Deserialize nested object from API call - Data is wrapped in parent JSON property

后端 未结 4 1740
春和景丽
春和景丽 2021-01-22 16:40

I have an API JSON response that wraps the data content in a data property, which looks like this:

{ 
   \"d         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-22 17:10

    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.

提交回复
热议问题