Anjali
Anjali

Reputation: 2698

trying to get curly braces in JSON than square brackets

I am trying to create the below JSON file. For this, I created a class called person and then I created a list inside the class called personDetails like so:

{
   "typeOfPerson":"",
   "personDetails":{
      "dateOfBirth":"12/20/2019"
   }
}



 public class person
    {


        public string typeOfPerson { get; set; }
        public List<PersonDetails> personDetails { get; set; } = new List<PersonDetails>();

    }

Below is my code to achieve the above JSON:

 public void test()
        {
            Person person = new Person();
            person.personDetails.Add(new PersonDetails { dateOfBirth = "12/20/2019" });

            string JSONresult = JsonConvert.SerializeObject(person);
            string jsonFormatted = JValue.Parse(JSONresult).ToString(Formatting.Indented);

        }

I get below JSON with above code rather than the one that I want

{
    "typeOfPerson": null,
    "personDetails": [
        {
            "dateOfBirth": "12/20/2019"
        }
    ]
}

After personDetails, I want curly braces instead of square brackets. With above code, I am getting square brackets not curly braces.

any help will be highly appreciated.

Upvotes: 0

Views: 1671

Answers (1)

Ben Krueger
Ben Krueger

Reputation: 1536

Square brackets denote that your JSON property is a collection. In your case, it's a List of PersonDetails. The curly brackets denote a singular object, so you would want your class person to be

public class person
{
    public string typeOfPerson { get; set; }
    public PersonDetails personDetails { get; set; }
}

and your test class would look like

public void test()
{
    Person person = new Person();
    person.personDetails = new PersonDetails() { dateOfBirth = "12/20/2019" };

    string JSONresult = JsonConvert.SerializeObject(person);
    string jsonFormatted = JValue.Parse(JSONresult).ToString(Formatting.Indented);
}

Upvotes: 1

Related Questions