2011-03-10 228 views
0

下面解析JSON的代码不起作用。我究竟做错了什么?需要帮助解析JSON

string jsonText = 
    @"{ 
     ""John Doe"":{ 
      ""email"":""[email protected]"", 
      ""ph_no"":""4081231234"", 
      ""address"":{      
       ""house_no"":""10"", 
       ""street"":""Macgregor Drive"", 
       ""zip"":""12345"" 
      } 
     }, 
     ""Jane Doe"":{ 
      ""email"":""[email protected]"", 
      ""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); 
    } 
} 

感谢

+1

什么是你的错误? – 2011-03-10 21:10:05

+0

你有什么样的问题,是不是编译,返回null,抛出异常? – 2011-03-10 21:10:17

+0

任何错误消息/例外?目前还不确定,但不要认为您使用了对象名称的双引号,例如“”John Doe“”成为John Doe。 – StuperUser 2011-03-10 21:10:25

回答

2

JSON文本不是Contact的列表,它是将名称映射到联系人的对象,因此List<Contact>是不合适的。

以下JSON文本匹配List<Contact>

var contactListJson = @"{ 
    ""email"":""[email protected]"", 
    ""ph_no"":""4081231234"", 
    ""address"":{      
     ""house_no"":""10"", 
     ""street"":""Macgregor Drive"", 
     ""zip"":""12345"" 
}, 
{ 
    ""email"":""[email protected]"", 
    ""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>

+0

我不控制传入的JSON输入你认为我应该改变我的类吗 – noobDotNet 2011-03-10 21:19:37

+0

反序列化到'Dictionary ' – orip 2011-03-10 21:20:58

+0

这样做的窍门谢谢。 – noobDotNet 2011-03-10 21:25:47

-1

http://www.json.org/

“A值可以是在双 引号的字符串或数字,或真或假 或为空,或物体或阵列。 这些结构可以嵌套”。

“”John Doe“”不是有效的字符串。如果你想保持引号,那么你可以使用这个:

“\”李四\“”

但我怀疑你只是想:

“李四”

+0

-1,它是一个C#逐字字符串文字 - '“”'被转换为单个'''' – orip 2011-03-10 21:24:09