Reputation: 49
I have a JSON in a web server like this :
{"My Book List": [{"ID":"5","TYPE":"History","TITLE":"Ekannoborti","PRICE":"200","IMAGE":"Ekannoborti.jpg","DOWNLOAD LINK":"http://www.starhostbd.com/"}],"success":3}
To deserialize it I have done so far :
public class Attributes
{
public string ID{ get; set; }
public string TYPE { get; set; }
public string TITLE { get; set; }
public string PRICE { get; set; }
public string IMAGE { get; set; }
public string DOWNLOADLINK { get; set; }
}
public class DataJsonAttributeContainer
{
public List<Attributes> attributes { get; set; }
//public Attributes attributes { get; set; }
}
public static T DeserializeFromJson<T>(string json)
{
T deserializedProduct = JsonConvert.DeserializeObject<T>(json);
return deserializedProduct;
}
& in my code :
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//var deserializedJSON = JsonConvert.DeserializeObject<Attributes>(e.Result);
var container = DeserializeFromJson<DataJsonAttributeContainer>(e.Result);
string asd = container.attributes[0].DOWNLOADLINK[0].ToString();
//string asd = deserializedJSON.DOWNLOADLINK[0].ToString();
}
The problem is : From debug wiindow i can see that data is assigned in e.Result but container remains null . How to solve this problem ? Please help !
Upvotes: 0
Views: 1033
Reputation: 5557
Actually both the above answers should solve your problem, you have to club them
public class MyBookList
{
public string ID { get; set; }
public string TYPE { get; set; }
public string TITLE { get; set; }
public string PRICE { get; set; }
public string IMAGE { get; set; }
[JsonProperty("DOWNLOAD LINK")]
public string DOWNLOADLINK { get; set; }
}
public class DataJsonAttributeContainer
{
[JsonProperty("My Book List")]
public List<MyBookList> MyBookList { get; set; }
public int success { get; set; }
}
and also
var container = DeserializeFromJson<DataJsonAttributeContainer>(e.Result);
string asd = container.attributes[0].DOWNLOADLINK.ToString();
Try with these classes. Should work.
Upvotes: 0
Reputation: 7233
Add a JsonProperty
attribute to the attributes
property to match the property name in the JSON, like so:
public class DataJsonAttributeContainer
{
[JsonProperty("My Book List")]
public List<Attributes> attributes { get; set; }
}
Also, you should add a JsonProperty
attribute to the Attributes.DOWNLOADLINK
property with "DOWNLOAD LINK" value in order for it to match the JSON property name.
Upvotes: 1
Reputation: 2477
At first glance I think the problem is at the DOWNLOADLINK property. Your server returns "DOWNLOAD LINK" but your property hasn't the space in it's name.
You should define the json representation at your property like this:
[JsonProperty(PropertyName = "DOWNLOAD LINK")]
public string DOWNLOADLINK { get; set; }
Hope this helps.
Upvotes: 0