2011-03-10 197 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