我正在使用. net JSON解析器,并想序列化我的配置文件,使其可读。所以不要:

{"blah":"v", "blah2":"v2"}

我想要更好的东西,比如:

{
    "blah":"v", 
    "blah2":"v2"
}

我的代码是这样的:

using System.Web.Script.Serialization; 

var ser = new JavaScriptSerializer();
configSz = ser.Serialize(config);
using (var f = (TextWriter)File.CreateText(configFn))
{
    f.WriteLine(configSz);
    f.Close();
}

当前回答

这对我很管用。以防有人在找VB。净版。

@imports System
@imports System.IO
@imports Newtonsoft.Json
    
Public Shared Function JsonPrettify(ByVal json As String) As String
  Using stringReader = New StringReader(json)

    Using stringWriter = New StringWriter()
      Dim jsonReader = New JsonTextReader(stringReader)
      Dim jsonWriter = New JsonTextWriter(stringWriter) With {
          .Formatting = Formatting.Indented
      }
      jsonWriter.WriteToken(jsonReader)
      Return stringWriter.ToString()
    End Using
  End Using
End Function

其他回答

这对我很管用。以防有人在找VB。净版。

@imports System
@imports System.IO
@imports Newtonsoft.Json
    
Public Shared Function JsonPrettify(ByVal json As String) As String
  Using stringReader = New StringReader(json)

    Using stringWriter = New StringWriter()
      Dim jsonReader = New JsonTextReader(stringReader)
      Dim jsonWriter = New JsonTextWriter(stringWriter) With {
          .Formatting = Formatting.Indented
      }
      jsonWriter.WriteToken(jsonReader)
      Return stringWriter.ToString()
    End Using
  End Using
End Function

onlineer使用Newtonsoft.Json.Linq:

string prettyJson = JToken.Parse(uglyJsonString).ToString(Formatting.Indented);

2023年更新

对于那些问我如何使用c#在。net中获得格式化JSON并想要看到如何立即使用它的人和一行爱好者。以下是缩进的JSON字符串一行代码:

有两种知名的JSON格式化器或解析器可以序列化:

Newtonsoft Json。网版:

using Newtonsoft.Json;

var jsonString = JsonConvert.SerializeObject(yourObj, Formatting.Indented);

.Net 7版本:

using System.Text.Json;

var jsonString = JsonSerializer.Serialize(yourObj, new JsonSerializerOptions { WriteIndented = true });

Json的简短示例代码。网络图书馆

private static string FormatJson(string json)
{
    dynamic parsedJson = JsonConvert.DeserializeObject(json);
    return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}

. net 5内置了在System.Text.Json命名空间下处理JSON解析、序列化、反序列化的类。下面是一个序列化器的例子,它将。net对象转换为JSON字符串,

using System.Text.Json;
using System.Text.Json.Serialization;

private string ConvertJsonString(object obj)
{
    JsonSerializerOptions options = new JsonSerializerOptions();
    options.WriteIndented = true; //Pretty print using indent, white space, new line, etc.
    options.NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals; //Allow NANs
    string jsonString = JsonSerializer.Serialize(obj, options);
    return jsonString;
}