I'm stuck on this issue with deserialization of a json file to a model in my asp.net application. So I've got a Json file that I get from an api call
"Motorola": [
{
"id": 534,
"vendor": "Motorola",
"type": "mobile_phone",
"model": "MOTO Z2 FORCE",
"models": [
{
"condition": "C",
"price": 5269,
"local_price": 29745,
"id": 3407,
"memory": "128 GB",
"color": "lunar_grey",
"product": 534
},
{
"condition": "D",
"price": 4699,
"local_price": 26527,
"id": 3407,
"memory": "128 GB",
"color": "lunar_grey",
"product": 534
}
...
And three models
public class TradeInResponseModel
{
public string BrandName { get; set; }
public List<TradeInBrandResponseModel> ModelsList { get; set; }
}
public class TradeInBrandResponseModel
{
public int Id { get; set; }
public string Vendor { get; set; }
public string Type { get; set; }
public string ModelName { get; set; }
public List<TradeInProductResponseModel> ModelProducts {get;set;}
}
public class TradeInProductResponseModel
{
public string Condition { get; set; }
public int Price { get; set; }
public int LocalPrice { get; set; }
public int Id { get; set; }
public string Memory { get; set; }
public string Color { get; set; }
public int ProductId { get; set; }
}
But after I run TradeInResponseModel tradeInResponseModel = JsonConvert.DeserializeObject<TradeInResponseModel>(responseMessage);
Where responseMessage
is a response from an api in form of json file
The model is null
Can't figure out what is going wrong here.
CodePudding user response:
Your JSON has a root object with a single property named Motorola
, not BrandName
.
In JavaScript (and JSON) objects are actually dictionaries. When you tell a serializer to deserialize the JSON data as a specific object it will try to match each dictionary key to an object property.
If you want to parse this JSON as a dictionary you should use Dictionary<string,List<TradeInResponseModel>>
as the type, eg :
var brands=JsonConvert.DeserializeObject<Dictionary<string,List<TradeInResponseModel>>>(
responseMessage);