从 c# 类创建序列化 JSON 列表类型对象



亲爱的,我正在使用 C# 类并制作 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>(),
}

我想要像这样的序列化对象,这些对象给出了如何放置一个值并使其生效。

"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"
}
], 

如何制作,请帮忙

使用 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);

它将对象序列化为 json,除了contactPerson

如果您需要使用根名称序列化对象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"}]}}

最新更新