Reputation: 35
The following code to parse JSON is not working. What am I doing wrong?
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);
}
}
Thanks
Upvotes: 0
Views: 236
Reputation: 75427
The JSON text isn't a list of Contact
s, 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"":""[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""
}";
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>
.
Upvotes: 2
Reputation: 722
"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"
Upvotes: -1
Reputation: 42246
Check out JSON.NET. It is well documented and highly extensible.
Upvotes: 1