JSON.net生成很多额外的方括号 [英] JSON.net Generating a lot of extra Square brackets
问题描述
我正在尝试使用JSON.Net生成以下json,但它添加了很多额外的方括号,我应该怎么做
需要杰森
I am trying to generate the following json with JSON.Net but it is adding alot of extra square brackets with what should I do
Needed 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)
))));
推荐答案
如果您已经有一个json字符串并希望将其映射到C#类构造,则可以使用Intigted Visual Studio函数将Json粘贴为类.
If you already have a json string and want it to map it to a C# class construct you can use the intigrated Visual Studio function Paste Json as Classes.
- 复制一些JSON
- 选择编辑"->选择性粘贴"->将JSON作为类粘贴"
如果这样做,Visual Studio将为您提供这两个类:
If you do so Visual Studio will make for you this two classes:
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#类.
With this Visual Studio tool you get a first idea how to map your json string to C# classes.
现在,如果您有一个类的对象,则可以简单地使用JsonConvert
Now if you have an object of your class, you can simply convert it with JsonConvert
var myObject = new Rootobject() { addUser = new Adduser() { idCard = 1, ...} };
var json = JsonConvert.SerializeObject(myObject);
要反序列化,只需致电:
To deserialize you simply call:
var myObject = JsonConvert.DeserializeObject<Rootobject>(json);
这篇关于JSON.net生成很多额外的方括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!