亲爱的所有人,我正在使用C#Class并制作json对象,但如何调用它。 并显示json对象我正在显示代码,请帮助我。
我在这里创建一个课程
public class Contacts
{
public List<PhoneMobile> phoneMobiles { get; set; }
public List<PhoneLandline> phoneLandlines { get; set; }
public List<Email> emails { get; set; }
}
public class PhoneMobile
{
public string phoneMobile { get; set; }
}
我在这里使用这样的课程
contacts = new Contacts
{
phoneMobiles = new List<PhoneMobile>
{
},
phoneLandlines = new List<PhoneLandline>(),
emails = new List<Email>(),
}
我想要像SerializeObject这样的对象给出了如何放置和制作一个值。
"contacts": {
"phoneMobiles": [
{
"phoneMobile": "8103267511"
}
],
"phoneLandlines": [
{
"phoneLandLineNumber": "8103267511"
}
],
"emails": [
{
"email": "testing@gmail.com"
}
]
},
"contactPerson": [
{
"personName": "TEST KARKHANA",
"owner": "null",
"email": "sanjeet.kumar@mponline.gov.in",
"phone": "8602865989"
}
],
如何制作请帮忙
答案 0 :(得分:3)
使用Json.Net库,您可以从Nuget下载它。 试试这个
var contactCollection = new Contacts
{
phoneMobiles = new List<PhoneMobile>
{
new PhoneMobile { phoneMobile = "8103267511" }
},
phoneLandlines = new List<PhoneLandline>()
{
new PhoneLandline { phoneLandLineNumber = "8103267511" }
},
emails = new List<Email>()
{
new Email { email = "testing@gmail.com" }
}
};
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(contacts);
它将除contactPerson
部分之外的对象序列化为json
如果您需要序列化根名称为contacts
的对象,请尝试
var collectionWrapper = new {
contacts = contactCollection
};
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(collectionWrapper);
然后结果将是:
{"contacts":{"phoneMobiles":[{"phoneMobile":"8103267511"}], "phoneLandlines":[{"phoneLandLineNumber":"8103267511"}], "emails":[{"email":"testing@gmail.com"}]}}