Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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# code

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)
                ))));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
430 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

  1. Copy some JSON
  2. Select Edit –> Paste Special –> Paste JSON As Classes

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; }
}

With this Visual Studio tool you get a first idea how to map your json string to C# classes.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...