0

I want to put an empty string in my JSON file rather than null value. Is it possible to do quickly with any C# utility or any other way

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

I have below C# code to get the above JSON:

public class person {

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

}

I have below C# code to get above JSON



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

above class creates this JSON:

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

This creates the JSON with null value in typeofperson. Is it possible to get empty string instead of null value? I can always initialize typeofperson="", but I have a huge JSON file and it has lot of empty strings . Any utility that can put "" instead of null in JSONREsult string.

any help is highly appreciated.

Anjali
  • 2,540
  • 7
  • 37
  • 77
  • 1
    Easy `public string typeOfPerson { get; set; } = string.Empty` – Tấn Nguyên Jun 04 '20 at 02:13
  • 1
    Like, I mentioned before, I can initialize each and property to empty string, but that will take lot of time. Is it quicker way to replace the entire JSON string null values to "" – Anjali Jun 04 '20 at 02:19

1 Answers1

-1

public class person {

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

}

you can try it like this.

honore
  • 1