简体   繁体   中英

C# Json consume out putting null values Asp.net core blazor

I have a web api that returns an array of type of object. Web api is working fine. When i attempt to deserialize the object into array of type object I only get null values. What am I missing?

Json:

{
    "results":"[{\"Name\":\"Rocky\",\"Breed\":\"Pitbull\",\"Color\":\"Brown\",\"Weight\":\"76\",\"OwnerUserId\":null,\"FamilyId\":\"1006949\"},{\"Name\":\"Casper\",\"Breed\":\"Terrier \",\"Color\":\"White \",\"Weight\":\"15\",\"OwnerUserId\":null,\"FamilyId\":\"1006949\"}]"
}

deserialize code:

public async Task values()
{
    var AJson = new root();
    var client = http.CreateClient();
    var response = await client.GetAsync("https://doggoapi2020.azurewebsites.net/Doggies/1006949");
    var responsebody = await response.Content.ReadAsStringAsync();
        
    AJson = Newtonsoft.Json.JsonConvert.DeserializeObject<root>(responsebody);
}

Model:

public class DoggoData
{
     
    [JsonProperty(PropertyName = "Name")]
    public string Name { get; set; }

    [JsonProperty(PropertyName = "Breed")]
    public string Breed { get; set; }
     
    public string Color { get; set; }
     
    public string Weight { get; set; }
      
    public string OwnerUserId { get; set; }
   
    public string FamilyId { get; set; }

}

public class root
{
    public DoggoData[] Jsonres { get; set; }
}

Change your root class to this. Json properties have to match the names

public class Root
{
    [JsonProperty("results")]
    public string Jsonres { get; set; }
}

Your results has a string and once you get that string, you can deserialize that to the List of DoggoData.

public class DoggoData
{

    [JsonProperty(PropertyName = "Name")]
    public string Name { get; set; }

    [JsonProperty(PropertyName = "Breed")]
    public string Breed { get; set; }

    public string Color { get; set; }

    public string Weight { get; set; }

    public string OwnerUserId { get; set; }

    public string FamilyId { get; set; }

}

public class Root
{
    [JsonProperty("results")]
    public string Jsonres { get; set; }
}

Root obj = JsonConvert.DeserializeObject<Root>(json);
List<DoggoData> listObj = JsonConvert.DeserializeObject<List<DoggoData>>(obj.Jsonres);

// Or
List<DoggoData> listObj2 = JsonConvert.DeserializeObject<List<DoggoData>>(JObject.Parse(json)["results"]);

Naming convention for the class name is with Uppercase first letter. I would recommend using Root instead of root .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM