i am trying to develop json feed below format
{
"contacts": [
{
"id": "c200",
"name": "Ravi Tamada",
"email": "ravi@gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
{
"id": "c201",
"name": "Johnny Depp",
"email": "johnny_depp@gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
]
}
using below codes
public class Phone
{
public string mobile { get; set; }
public string home { get; set; }
public string office { get; set; }
}
public class Cont
{
public string sno { get; set; }
public string name { get; set; }
public string em { get; set; }
public string address { get; set; }
public string gender { get; set; }
public Phone phone { get; set; }
}
public class RootObject
{
public List<Cont> contacts { get; set; }
}
and
var objectToSerialize = new RootObject();
// var aa = new Cont();
objectToSerialize.contacts = new List<Cont>
{
new Cont { sno = "test1", name = "index1" , address = "index1",gender="male",em="scd", phone={mobile="ff",home="ff",office="ff"}}
// new Item { name = "test2", index = "index2" }
};
JavaScriptSerializer serializer = new JavaScriptSerializer();
Response.Write(serializer.Serialize(objectToSerialize));
using this code unable to get my output ,i am also getting Object reference not set to an instance ..
i have added my all code .
any one help what is wrong in my code
This is the problem, in your object initializer:
phone={mobile="ff",home="ff",office="ff"}
That's trying to set properties of an existing Phone
object. In other words, it's performing:
var tmp = new Cont();
tmp.sno = "test1";
...
tmp.phone.mobile = "ff";
tmp.phone.home = "ff";
...
... without ever setting the value of tmp.phone
to a non-null reference.
You either want:
phone=new Phone {mobile="ff",home="ff",office="ff"}
Or you need to change your Cont
class to give it a constructor to initialize Phone
:
public Cont()
{
phone = new Phone();
}
I'd also strongly advise you to follow .NET naming conventions for your properties, and give your class a full name of Contact
rather than Cont
. Avoid abbreviating pointlessly.
You should be able to configure the serializer to use lower-case names in the JSON without making the .NET names ugly.
See more on this question at Stackoverflow