0

以下解析 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);
    }
}

谢谢

4

3 回答 3

2

JSON 文本不是Contacts 的列表,它是一个将姓名映射到联系人的对象,因此 aList<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-10T21:15:11.177 回答
1

查看JSON.NET。它有据可查且高度可扩展。

于 2011-03-10T21:14:03.280 回答
-1

http://www.json.org/

“一个值可以是双引号中的字符串,也可以是数字,或者真假或空值,或者对象或数组。这些结构可以嵌套。”

""John Doe"" is not a valid string. If you want to keep the quotes then you would use this:

"\"John Doe\""

but I suspect you just want:

"John Doe"

于 2011-03-10T21:19:01.310 回答