0

I am not able to serialize the following property correctly

pubic string[] names {get;set;}

Many times names array is null and at the time of serialization it is coming as "names":[""]

 JsonConvert.SerializeObject(Requestobj, settings);

How can I change from "names" : [""] to "names" : []

rachit
  • 5
  • 3
  • 6
    Looks like your array isn't empty, it has a single, empty string in it. How are you setting the names property? – Elliveny Oct 17 '22 at 15:48
  • You should be able to reverse this: https://stackoverflow.com/questions/23830206/json-convert-empty-string-instead-of-null/23832417#23832417 – sr28 Oct 17 '22 at 15:58

1 Answers1

1

just simple string replacing will help you

json=json.Replace("[\"\"]","[]");

But it is better to fix the API if you have an access. The API problem is that it doesn't create an empty array, it creates an array with a single, empty string in it.

var test = new { names = new string[] {""}};
var json=JsonConvert.SerializeObject(test); // {"names":[""]}

var test = new { names = new string[] {}};
var json=JsonConvert.SerializeObject(test); // {"names":[]}

Serge
  • 40,935
  • 4
  • 18
  • 45