以下解析JSON的代码不起作用。我做错了什么?
string jsonText =
@"{
""John Doe"":{
""email"":""jdoe@gmail.com"",
""ph_no"":""4081231234"",
""address"":{
""house_no"":""10"",
""street"":""Macgregor Drive"",
""zip"":""12345""
}
},
""Jane Doe"":{
""email"":""jane@gmail.com"",
""ph_no"":""4081231111"",
""address"":{
""house_no"":""56"",
""street"":""Scott Street"",
""zip"":""12355""
}
}
}"
public class Address {
public string house_no { get; set; }
public string street { get; set; }
public string zip { get; set; }
}
public class Contact {
public string email { get; set; }
public string ph_no { get; set; }
public Address address { get; set; }
}
public class ContactList
{
public List<Contact> Contacts { get; set; }
}
class Program
{
static void Main(string[] args)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
ContactList cl = serializer.Deserialize<ContactList>(jsonText);
}
}谢谢
发布于 2011-03-11 05:15:11
JSON文本不是Contact的列表,它是一个将姓名映射到联系人的对象,因此List<Contact>是不合适的。
下面的JSON文本与List<Contact>匹配
var contactListJson = @"{
""email"":""jdoe@gmail.com"",
""ph_no"":""4081231234"",
""address"":{
""house_no"":""10"",
""street"":""Macgregor Drive"",
""zip"":""12345""
},
{
""email"":""jane@gmail.com"",
""ph_no"":""4081231111"",
""address"":{
""house_no"":""56"",
""street"":""Scott Street"",
""zip"":""12355""
}";因此,下面的JSON将匹配ContactList
var jsonText = string.Format(@"{ ""Contacts"" : ""{0}"" }", contactListJson);编辑:要反序列化现有的JSON格式,请尝试反序列化为Dictionary<string, Contact>。
发布于 2011-03-11 05:14:03
查看JSON.NET。它有很好的文档和高度的可扩展性。
发布于 2011-03-11 05:19:01
http://www.json.org/
“值可以是双引号中的字符串,也可以是数字,也可以是true、false或null,也可以是对象或数组。这些结构可以嵌套。”
""John Doe"“不是有效的字符串。如果您想保留引号,则可以使用以下命令:
“\”无名氏\“”
但我怀疑你只是想:
“无名氏”
https://stackoverflow.com/questions/5265921
复制相似问题