0

I'm trying to generate an indented JSON output using JSON.Net. The first code does not work

var data = new WebClient().DownloadString(url);
var json = JsonConvert.SerializeObject(data, Formatting.Indented);

However, this second code does work

var data = new WebClient().DownloadString(url);
var json = JValue.Parse(data).ToString(Formatting.Indented);

I'm a bit confused why both versions don't give the same output.

insomniac
  • 192
  • 1
  • 3
  • 16
  • 6
    In the first example you are **double-serializing** a JSON string. I.e. a string that is already JSON is being serialized as a JSON string literal. Json.NET will not reformat or otherwise modify a string literal during serialization. In the second case, you need to be aware that [there is no static method `JValue.Parse()`](https://stackoverflow.com/a/38212978/3744182), so you are actually calling the `JToken.Parse()` method on the base class. Thus you deserialize the JSON into a `JToken`, then re-serialize it to JSON, which will cause it to get reformatted. – dbc Apr 04 '20 at 23:06
  • In the first example why are you calling SerializeObject? What is the point? – Jonathan Alfaro Apr 05 '20 at 04:17
  • Thanks, dbc. _"Json.NET will not reformat or otherwise modify a string literal during serialization"_ answered my question. – insomniac Apr 05 '20 at 09:06

0 Answers0