C# 对象引用未设置为json中对象错误的实例
我正在尝试开发以下格式的json提要C# 对象引用未设置为json中对象错误的实例,c#,.net,json,C#,.net,Json,我正在尝试开发以下格式的json提要 { "contacts": [ { "id": "c200", "name": "Ravi Tamada", "email": "ravi@gmail.com", "address": "xx-xx-xxxx,x - street, x - country", "gender"
{
"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; }
}
及
使用此代码无法获取输出,我还获取了未设置为实例的对象引用
我已经添加了我的所有代码
任何人都可以帮助我找出代码中的错误这是对象初始值设定项中的问题:
phone={mobile="ff",home="ff",office="ff"}
尝试设置现有电话对象的属性。换句话说,它正在执行:
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类,为其提供一个构造函数来初始化手机:
我还强烈建议您对属性遵循.NET命名约定,给类一个Contact全名,而不是Cont。避免无意义的缩写
您应该能够将序列化程序配置为在JSON中使用小写名称,而不会使.NET名称难看。在对象初始值设定项中,这就是问题所在:
phone={mobile="ff",home="ff",office="ff"}
尝试设置现有电话对象的属性。换句话说,它正在执行:
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类,为其提供一个构造函数来初始化手机:
我还强烈建议您对属性遵循.NET命名约定,给类一个Contact全名,而不是Cont。避免无意义的缩写
您应该能够将序列化程序配置为在JSON中使用小写名称,而不会使.NET名称难看
试一试
尝试初始化电话属性
试一试
尝试初始化电话属性