Fah*_*med 1 c# json.net windows-phone-7 deserialization
我有一个这样的Json:
[{"id":"54718","title":"Khaleda to visit China","corres":"Special Correspondent","details":"DHAKA: On a 7-day visit, opposition BNP Chairperson Khaleda Zia will leave Dhaka for China on October 14.","photo":"2012October\/SM\/Khaleda-new-sm20121003132805.jpg"}]
Run Code Online (Sandbox Code Playgroud)
为了解析这个Json,到目前为止我做了:
public class Attributes
{
[JsonProperty("id")]
public string ID{ get; set; }
[JsonProperty("title")]
public string TITLE { get; set; }
[JsonProperty("corres")]
public string CORRES { get; set; }
[JsonProperty("details")]
public string DETAIL { get; set; }
[JsonProperty("photo")]
public string LINK { get; set; }
}
public class DataJsonAttributeContainer
{
public List<Attributes> NewsList{ get; set; }
//public Attributes attributes { get; set; }
}
public static T DeserializeFromJson<T>(string json)
{ //I'm getting the error here
T deserializedProduct = JsonConvert.DeserializeObject<T>(json);
return deserializedProduct;
}
Run Code Online (Sandbox Code Playgroud)
在我的代码中:
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//parse data
var container = DeserializeFromJson<DataJsonAttributeContainer>(e.Result);
//load into list
for (i = 0; i < container.NewsList.Count ; i++)
{
newData[i] = new data();
newData[i].id = container.NewsList[i].ID;
newData[i].title = container.NewsList[i].TITLE;
newData[i].price = container.NewsList[i].CORRES;
newData[i].image = container.NewsList[i].DETAIL;
newData[i].link = container.NewsList[i].LINK;
}
Run Code Online (Sandbox Code Playgroud)
问题是: container从Web服务器获取json,我可以在调试器中看到它,但它在反序列化时出现异常.有人可以帮忙吗?我得到的例外情况:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'BanglaNewsPivot.MainPage+DataJsonAttributeContainer' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.Path '', line 1, position 1.
Run Code Online (Sandbox Code Playgroud)
你的json是一个数组(不是包含数组的单个对象).打电话给你DeserializeFromJson,如下
var attrs = DeserializeFromJson<List<Attributes>>(e.Result);
Run Code Online (Sandbox Code Playgroud)
足够.
- 编辑 -
foreach (var attr in attrs)
{
Console.WriteLine("{0} {1}", attr.ID, attr.TITLE);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3247 次 |
| 最近记录: |