我正在尝试以格式
开发json feed{
"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"
}
},
]
}
使用以下代码
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; }
}
和
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));
使用此代码无法获取我的输出,我也将对象引用未设置为实例..
我添加了我的所有代码。
任何一个人帮助我的代码出错了
答案 0 :(得分:3)
这是你的对象初始化程序中的问题:
phone={mobile="ff",home="ff",office="ff"}
这是尝试设置现有 Phone
对象的属性。换句话说,它正在执行:
var tmp = new Cont();
tmp.sno = "test1";
...
tmp.phone.mobile = "ff";
tmp.phone.home = "ff";
...
...没有将tmp.phone
的值设置为非空引用。
你要么:
phone=new Phone {mobile="ff",home="ff",office="ff"}
或者您需要更改Cont
类,以便为其初始化Phone
提供构造函数:
public Cont()
{
phone = new Phone();
}
我还强烈建议您遵循属性的.NET命名约定,并为您的班级提供Contact
而不是Cont
的全名。避免毫无意义地缩写。
您应该能够将序列化程序配置为在JSON中使用小写名称,而不会使.NET名称变得丑陋。
答案 1 :(得分:0)
尝试初始化手机属性