需要帮助解析JSON

时间:2011-03-10 21:07:32

标签: c# json javascriptserializer

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

由于

3 个答案:

答案 0 :(得分:2)

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>

答案 1 :(得分:1)

结帐JSON.NET。它有很好的文档记录和高度可扩展性。

答案 2 :(得分:-1)

http://www.json.org/

  

“值可以是double的字符串   引号,数字,或真或假   或null,或对象或数组。   这些结构可以嵌套。“

“”John Doe“”不是有效的字符串。如果你想保留报价,那么你可以使用:

“\”John Doe \“”

但我怀疑你只是想要:

“John Doe”