我正在尝试使用JSON.Net生成以下json,但它添加了许多额外的方括号,我应该怎么做 需要Json
{
"addUser": {
"idCard": "xxx",
"firstName": "xxx",
"surname": "Muscat",
"isActive": true,
"titleDesc": "xx",
"genderDesc": "Female",
"emailAddress":"",
"mobileNumber":"",
"telephoneNumber":"",
"dob":""
}
}
C#代码
var obj = new JObject();
obj.Add(
new JProperty("addUser",
new JArray(
new JObject(
new JProperty("idCard", doct.First().idCard.PadLeft(8, '0')),
new JProperty ("firstName", det.First().PersonName),
new JProperty("surname", det.First().PersonSurname),
new JProperty("isActive", true),
new JProperty("titleDesc", ""),
new JProperty("genderDesc", det.First().PersonGenderDesc),
new JProperty("emailAddress", ""),
new JProperty("mobileNumber", ""),
new JProperty("telephoneNumber", ""),
new JProperty("dob", det.First().PersonBirthDate)
))));
答案 0 :(得分:6)
如果您已经有一个json字符串并希望它将它映射到C#类构造,您可以使用已插入的Visual Studio函数将Json粘贴为类。
如果您这样做,Visual Studio将为您提供这两个类:
public class Rootobject
{
public Adduser addUser { get; set; }
}
public class Adduser
{
public string idCard { get; set; }
public string firstName { get; set; }
public string surname { get; set; }
public bool isActive { get; set; }
public string titleDesc { get; set; }
public string genderDesc { get; set; }
public string emailAddress { get; set; }
public string mobileNumber { get; set; }
public string telephoneNumber { get; set; }
public string dob { get; set; }
}
使用此Visual Studio工具,您将首先了解如何将json字符串映射到C#类。
现在,如果您有班级的对象,则可以使用JsonConvert
var myObject = new Rootobject() { addUser = new Adduser() { idCard = 1, ...} };
var json = JsonConvert.SerializeObject(myObject);
要反序列化,只需致电:
var myObject = JsonConvert.DeserializeObject<Rootobject>(json);