这是我的JSON字符串:
"{\"1\":{\"Name\":\"macintosh\",\"ShortDescription\":\"red\",\"LongDescription\":\"dfhdfh\"},\"2\":{\"Name\":\"macintosh\",\"ShortDescription\":\"red\",\"LongDescription\":\"dfhdfh\"},\"7\":{\"Name\":\"macintosh\",\"ShortDescription\":\"red\",\"LongDescription\":\"dfhdfh\"},\"8\":{\"Name\":\"macintosh\",\"ShortDescription\":\"red\",\"LongDescription\":\"dfhdfh\"},\"9\":{\"Name\":\"macintosh\",\"ShortDescription\":\"red\",\"LongDescription\":\"dfhdfh\"},\"10\":{\"Name\":\"macintosh\",\"ShortDescription\":\"red\",\"LongDescription\":\"dfhdfh\"}}"
这是JSON对象:
{
"1": {
"Name": "macintosh",
"ShortDescription": "red",
"LongDescription": "dfhdfh"
},
"2": {
"Name": "macintosh",
"ShortDescription": "red",
"LongDescription": "dfhdfh"
},
"7": {
"Name": "macintosh",
"ShortDescription": "red",
"LongDescription": "dfhdfh"
},
"8": {
"Name": "macintosh",
"ShortDescription": "red",
"LongDescription": "dfhdfh"
},
"9": {
"Name": "macintosh",
"ShortDescription": "red",
"LongDescription": "dfhdfh"
},
"10": {
"Name": "macintosh",
"ShortDescription": "red",
"LongDescription": "dfhdfh"
}
}
以下是我的课程:
public class MyModel
{
public string Name { get; set; }
public string ShortDescription { get; set; }
public string LongDescription { get; set; }
}
public class Friends
{
public Dictionary<int, MyModel> data { get; set; }
}
以下是我尝试反序列化的方法:
Friends facebookFriends = new JavaScriptSerializer().Deserialize<Friends>(theJsonString);
但后来facebookFriends.data
给了我null
的价值。我做错了什么?
答案 0 :(得分:1)
尝试:
var friends = new JavaScriptSerializer().Deserialize<Dictionary<string, MyModel>>(theJsonString);
答案 1 :(得分:0)
有几个问题。反序列化器希望看到一个data
对象,您在JSON字符串中没有这个对象。此外,&#34;键&#34;你有字符串,而不是整数。所以你想要这样的东西:
Friends facebookFriends = new Friends();
facebookFriends.data = new JavaScriptSerializer().Deserialize<Dictionary<string, MyModel>>(theJsonString);
您还需要更新您的模型:
public class Friends
{
public Dictionary<string, MyModel> data { get; set; }
}