我正在使用. 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();
}

用JavaScriptSerializer来完成这个任务会很困难。

试试JSON.Net。

对JSON进行了少量修改。净的例子

using System;
using Newtonsoft.Json;

namespace JsonPrettyPrint
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Product product = new Product
                {
                    Name = "Apple",
                    Expiry = new DateTime(2008, 12, 28),
                    Price = 3.99M,
                    Sizes = new[] { "Small", "Medium", "Large" }
                };

            string json = JsonConvert.SerializeObject(product, Formatting.Indented);
            Console.WriteLine(json);

            Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
        }
    }

    internal class Product
    {
        public String[] Sizes { get; set; }
        public decimal Price { get; set; }
        public DateTime Expiry { get; set; }
        public string Name { get; set; }
    }
}

结果

{
  "Sizes": [
    "Small",
    "Medium",
    "Large"
  ],
  "Price": 3.99,
  "Expiry": "\/Date(1230447600000-0700)\/",
  "Name": "Apple"
}

文档:序列化对象


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

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

如果你有一个JSON字符串,想要“美化”它,但不想将它序列化到一个已知的c#类型,那么下面的方法就可以了(使用JSON.NET):

using System;
using System.IO;
using Newtonsoft.Json;

class JsonUtil
{
    public static string JsonPrettify(string json)
    {
        using (var stringReader = new StringReader(json))
        using (var stringWriter = new StringWriter())
        {
            var jsonReader = new JsonTextReader(stringReader);
            var jsonWriter = new JsonTextWriter(stringWriter) { Formatting = Formatting.Indented };
            jsonWriter.WriteToken(jsonReader);
            return stringWriter.ToString();
        }
    }
}

你可以使用以下标准方法来获取格式化的Json

JsonReaderWriterFactory。CreateJsonWriter(流流,编码编码,bool ownsStream, bool缩进,字符串indentChars)

只设置"缩进==true"

试试这样的方法

    public readonly DataContractJsonSerializerSettings Settings = 
            new DataContractJsonSerializerSettings
            { UseSimpleDictionaryFormat = true };

    public void Keep<TValue>(TValue item, string path)
    {
        try
        {
            using (var stream = File.Open(path, FileMode.Create))
            {
                //var currentCulture = Thread.CurrentThread.CurrentCulture;
                //Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

                try
                {
                    using (var writer = JsonReaderWriterFactory.CreateJsonWriter(
                        stream, Encoding.UTF8, true, true, "  "))
                    {
                        var serializer = new DataContractJsonSerializer(type, Settings);
                        serializer.WriteObject(writer, item);
                        writer.Flush();
                    }
                }
                catch (Exception exception)
                {
                    Debug.WriteLine(exception.ToString());
                }
                finally
                {
                    //Thread.CurrentThread.CurrentCulture = currentCulture;
                }
            }
        }
        catch (Exception exception)
        {
            Debug.WriteLine(exception.ToString());
        }
    }

注意线条

    var currentCulture = Thread.CurrentThread.CurrentCulture;
    Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
    ....
    Thread.CurrentThread.CurrentCulture = currentCulture;

对于某些类型的xml序列化器,您应该使用InvariantCulture来避免在具有不同区域设置的计算机上反序列化期间出现异常。例如,double或DateTime的无效格式有时会导致错误。

在反序列化

    public TValue Revive<TValue>(string path, params object[] constructorArgs)
    {
        try
        {
            using (var stream = File.OpenRead(path))
            {
                //var currentCulture = Thread.CurrentThread.CurrentCulture;
                //Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

                try
                {
                    var serializer = new DataContractJsonSerializer(type, Settings);
                    var item = (TValue) serializer.ReadObject(stream);
                    if (Equals(item, null)) throw new Exception();
                    return item;
                }
                catch (Exception exception)
                {
                    Debug.WriteLine(exception.ToString());
                    return (TValue) Activator.CreateInstance(type, constructorArgs);
                }
                finally
                {
                    //Thread.CurrentThread.CurrentCulture = currentCulture;
                }
            }
        }
        catch
        {
            return (TValue) Activator.CreateInstance(typeof (TValue), constructorArgs);
        }
    }

谢谢!


修饰现有JSON的最短版本:(编辑:使用JSON.net)

JToken.Parse("mystring").ToString()

输入:

{"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } }}

输出:

{
  "menu": {
    "id": "file",
    "value": "File",
    "popup": {
      "menuitem": [
        {
          "value": "New",
          "onclick": "CreateNewDoc()"
        },
        {
          "value": "Open",
          "onclick": "OpenDoc()"
        },
        {
          "value": "Close",
          "onclick": "CloseDoc()"
        }
      ]
    }
  }
}

漂亮地打印一个对象:

JToken.FromObject(myObject).ToString()

首先我想在Duncan Smart的帖子下添加评论,但不幸的是,我还没有足够的声誉来留下评论。我在这里试试。

我只是想警告一下副作用。

JsonTextReader在内部将json解析为类型化的jtoken,然后将它们序列化回来。

例如,如果您的原始JSON是

{ "double":0.00002, "date":"\/Date(1198908717056)\/"}

美化之后你得到

{ 
    "double":2E-05,
    "date": "2007-12-29T06:11:57.056Z"
}

当然,这两个json字符串是等价的,并且将反序列化为结构上相等的对象,但如果您需要保留原始字符串值,则需要考虑这一点


onlineer使用Newtonsoft.Json.Linq:

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

下面是一个使用微软System.Text.Json库的解决方案:

static string FormatJsonText(string jsonString)
{
    using var doc = JsonDocument.Parse(
        jsonString,
        new JsonDocumentOptions
        {
            AllowTrailingCommas = true
        }
    );
    MemoryStream memoryStream = new MemoryStream();
    using (
        var utf8JsonWriter = new Utf8JsonWriter(
            memoryStream,
            new JsonWriterOptions
            {
                Indented = true
            }
        )
    )
    {
        doc.WriteTo(utf8JsonWriter);
    }
    return new System.Text.UTF8Encoding()
        .GetString(memoryStream.ToArray());
}

这对我很管用。以防有人在找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

使用System.Text.Json设置JsonSerializerOptions。writeindent = true:

JsonSerializerOptions options = new JsonSerializerOptions { WriteIndented = true };
string json = JsonSerializer.Serialize<Type>(object, options);

所有这些都可以在一行中完成:

string jsonString = JsonConvert.SerializeObject(yourObject, Formatting.Indented);

Net Core App

var js = JsonSerializer.Serialize(obj, new JsonSerializerOptions {
             WriteIndented = true
         });

下面的代码为我工作:

JsonConvert.SerializeObject(JToken.Parse(yourobj.ToString()))

对于使用。net Core 3.1的UTF8编码的JSON文件,我最终能够使用基于微软的信息:https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to#utf8jsonreader-utf8jsonwriter-and-jsondocument的JsonDocument

string allLinesAsOneString = string.Empty;
string [] lines = File.ReadAllLines(filename, Encoding.UTF8);
foreach(var line in lines)
    allLinesAsOneString += line;

JsonDocument jd = JsonDocument.Parse(Encoding.UTF8.GetBytes(allLinesAsOneString));
var writer = new Utf8JsonWriter(Console.OpenStandardOutput(), new JsonWriterOptions
{
    Indented = true
});
JsonElement root = jd.RootElement;
if( root.ValueKind == JsonValueKind.Object )
{
    writer.WriteStartObject();
}
foreach (var jp in root.EnumerateObject())
    jp.WriteTo(writer);
writer.WriteEndObject();

writer.Flush();

我有一些非常简单的方法。你可以输入任何需要转换成json格式的对象:

private static string GetJson<T> (T json)
{
    return JsonConvert.SerializeObject(json, 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;
}

using System.Text.Json;
...
var parsedJson = JsonSerializer.Deserialize<ExpandoObject>(json);
var options = new JsonSerializerOptions() { WriteIndented = true };
return JsonSerializer.Serialize(parsedJson, options);

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 });