开发者

Need help parsing JSON

The following code to parse JSON is not working. What am I doing wrong?

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开发者_如何学Python 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);
    }
}

Thanks


The JSON text isn't a list of Contacts, it's an object mapping a name to a contact, so a List<Contact> is inappropriate.

The following JSON text matches 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""
}";

so the following JSON would match ContactList:

var jsonText = string.Format(@"{ ""Contacts"" : ""{0}"" }", contactListJson);

EDIT: To deserialize the existing JSON format, try deserializing into Dictionary<string, Contact>.


Check out JSON.NET. It is well documented and highly extensible.


http://www.json.org/

"A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested."

""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"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜