skip to Main Content

I use Visual Studio 2022 and download Newtonsoft.Json in NuGet package manager, my dict like:

var param_dict = new Dictionary<string, object>
{
    { "config_path", "D:WORK_2023Helloworld in C" },
};

Now I want to save it as a JSON file, so I tried this code:

string json = JsonConvert.SerializeObject(param_dict, Formatting.Indented);
File.WriteAllText(param_file_path, json); 

The problem is how to change the Formatting.Indented value, I found its default value is 1, but I want to change to 4, but it cannot work if Formatting.Indented = 4;.

Or I need to change other namespace, like Json.NET?

2

Answers


  1. Formatting.Indented – only specifies whether formatting should be used. In fact, the introduction of this enumeration at the present time is nonsense. Usined a bool flag instead would be sufficient. Perhaps the original intention of the package developers was to have a wider range of values.

    What you need, I think, is the Indentation property.

    See Formatting Enumeration and JsonTextWriterIndentation Property.

    Login or Signup to reply.
  2. You can use JsonTextWriter with appropriate Indentation property:

    using var streamWriter = new StreamWriter(param_file_path);
    using var jsonWriter = new JsonTextWriter(streamWriter);
    jsonWriter.Indentation = 4;
    
    var serializer = JsonSerializer.CreateDefault(new JsonSerializerSettings{ Formatting = Formatting.Indented });
    serializer.Serialize(jsonWriter, param_dict);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search