1

I am writing a method to write the content from a URL to disk as JSON. It should only write the response body content, and should ignore null values, i.e., if it encounters a null value it should not be written to the file. In order to just get the body content from the response I use the ReadAsStringAsync method to convert it to a string. I then create a new JObject from the string, and to remove the null values I use NullValueHandling.Ignore when serializing, however when I open the Json file there are still null values present. Below is my code:

var response = await client.GetAsync(url);
var data = await response.Content.ReadAsStringAsync();
        
JObject jsonObj = JObject.Parse(data);

var result = JsonConvert.SerializeObject(jsonObj, Formatting.Indented,
       new JsonSerializerSettings()
       {
            NullValueHandling = NullValueHandling.Ignore
       });

I have tried solutions such as the one found here, but that leads to errors of its own.

Is there a way to be able to skip null values, while only saving the response body and not the headers?

irl_steve
  • 13
  • 5
  • I can reproduce what you're seeing. [See here](https://dotnetfiddle.net/SpPfSa). If I use a class, however, it doesn't exhibit this behaviour and works correctly. I note that [`JObject.ToString`](https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JObject.htm) doesn't take a settings or NullValueHandling option, and I wonder if `Serialize` is just calling this method internally for `JObject`. In short: I think it might be a bug in JSON.NET. – ProgrammingLlama Feb 18 '22 at 09:50
  • I found a [related issue](https://github.com/JamesNK/Newtonsoft.Json/issues/1058). The maintainer states that "A JObject isn't serialized. It is written as is." – ProgrammingLlama Feb 18 '22 at 09:51
  • @Llama https://stackoverflow.com/a/29259032/968671 already explains why JValue in JObject is not `null` but `JTokenType.Null` – Mat Feb 18 '22 at 09:53
  • @Mat I'm having trouble understanding the relevance of your comment. Can you explain it, please? – ProgrammingLlama Feb 18 '22 at 09:54
  • It's not a bug in Newtonsoft.Json package, it's intended behaviour. But I aggree that this behaviour is stupid ;-) – Mat Feb 18 '22 at 09:56
  • Ah, I see. Yeah, I agree. It's misleading to be able to serialize it through `SerializeObject` but have it not apply the settings specified. :-( – ProgrammingLlama Feb 18 '22 at 09:57
  • same behaviour in System.Text.Json https://dotnetfiddle.net/WxZwce – Mat Feb 18 '22 at 10:07

0 Answers0