user7071176
user7071176

Reputation:

How to write a JSON file in pretty format using .Net

When writing a json string to a file using the following code below, it doesn't show up in a pretty format when editing the file, but rather just shows up as a string format. If I use .Net fiddle, the console output is correct and it looks good. How do I write the json string to a file, so when editing /w say notepad++ it shows up in a pretty format. Can someone help?

.Net Fiddle code for console output which works fine

public class Program
{
    public static void Main()
    {
        String sPrettyStr;
        var item = "{\"messageType\":\"0\",\"code\":\"1\"}";
        sPrettyStr = JValue.Parse(item).ToString(Newtonsoft.Json.Formatting.Indented);
        Console.WriteLine(sPrettyStr);
    }
}

.Net Fiddle console output

{
  "messageType": "0",
  "code": "1"
}

But when writing a formatted json string to file using this

File.WriteAllText(c:/test.json,JValue.Parse(item).ToString(Newtonsoft.Json.Formatting.Indented)) 

I get this file output when edited w/ notepad++

"{\\\"messageType\\\":\\\"0\\\",\\\"code\\\"}"

Upvotes: 2

Views: 13534

Answers (2)

djsp
djsp

Reputation: 19

Try this code:

var item = "{\"messageType\":\"0\",\"code\":\"1\"}";
JToken token = JToken.Parse(item);
JObject json = JObject.Parse((string) token);
Console.WriteLine(json);

Upvotes: 0

HenryMigo
HenryMigo

Reputation: 164

After having a gander and attempting myself this is what I found: You first have to deserialize the string then serialize it again.

EDIT: Took your code as well and got the desired output also like others in comment have said. I tweaked to use JToken instead of JValue and all is good.

using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace StackOverflow
{
    class Program
    {
        static void Main(string[] args)
        {
            var item = "{\"messageType\":\"0\",\"code\":\"1\"}";

            var t = JsonConvert.DeserializeObject(item);
            var x = JsonConvert.SerializeObject(t, Formatting.Indented);

            string sPrettyStr;
            var item2 = "{\"messageType\":\"0\",\"code\":\"1\"}";
            sPrettyStr = JToken.Parse(item2).ToString(Formatting.Indented);

            Console.WriteLine(x);
            Console.WriteLine(sPrettyStr);
            Console.ReadLine();
        }
    }
}

Credit to Frank from here

Upvotes: 4

Related Questions