Reputation: 77
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; }
}
Upvotes: 0
Views: 730
Reputation: 11364
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
.
Upvotes: 2