如何使用 C# 在 .NET 中获取格式化 JSON?

问题描述 投票:0回答:21

我正在使用 .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();
}
c# .net json javascriptserializer
21个回答
328
投票

您将很难使用 JavaScriptSerializer 来完成此任务。

尝试JSON.Net

对 JSON.Net 示例进行少量修改

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"
}

文档:序列化对象


241
投票

Json.Net 库的较短示例代码

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

160
投票

如果您有一个 JSON 字符串并想要“美化”它,但不想将其序列化为已知的 C# 类型或从已知的 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();
        }
    }
}

142
投票

美化现有 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()
    

66
投票
Oneliner 使用

Newtonsoft.Json.Linq

:

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

57
投票
网络核心应用程序

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

35
投票
所有这些都可以通过简单的一行完成:

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

28
投票
这是使用 Microsoft 的

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

27
投票
2023 更新

对于那些问我如何使用 C# 在 .NET 中获取格式化 JSON 并想了解

如何立即使用它单行爱好者的人。以下是缩进的 JSON 字符串一行代码:

有 2 个众所周知的 JSON 格式化程序或解析器可供序列化:

Newtonsoft Json.Net 版本:

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

13
投票
您可以使用以下标准方法来获取格式化的 Json

JsonReaderWriterFactory.CreateJsonWriter(Stream 流、Encoding 编码、bool ownsStream、bool indent、string indentChars)

仅设置

“indent==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 以避免在具有不同区域设置的计算机上反序列化期间出现异常。例如,doubleDateTime的无效格式有时会导致它们。

用于反序列化

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

谢谢!


8
投票
使用

System.Text.Json

 设置 
JsonSerializerOptions.WriteIndented = true
:

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

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

2
投票
首先我想在 Duncan Smart 帖子下添加评论,但不幸的是我还没有足够的声誉来发表评论。所以我会在这里尝试一下。

我只是想警告副作用。

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

例如,如果您的原始 JSON 是

{ "double":0.00002, "date":"\/Date(1198908717056)\/"}
美化后你得到

{ "double":2E-05, "date": "2007-12-29T06:11:57.056Z" }
当然,两个 json 字符串是等效的,并且会反序列化为结构上相同的对象,但是如果您需要保留原始字符串值,则需要考虑这一点


1
投票
这对我有用。如果有人正在寻找 VB.NET 版本。

@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
    

1
投票
我有一些非常简单的方法。您可以将任何要转换为 json 格式的对象作为输入:

private static string GetJson<T> (T json) { return JsonConvert.SerializeObject(json, Formatting.Indented); }
    

1
投票
.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; }
    

0
投票
下面的代码对我有用:

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

0
投票
对于使用 .NET Core 3.1 的 UTF8 编码 JSON 文件,我终于能够根据 Microsoft 的以下信息使用 JsonDocument:

https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text -json-how-to#utf8jsonreader-utf8jsonwriter-and-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();
    

0
投票
var formattedJson = System.Text.Json.JsonSerializer.Serialize(myresponse, new JsonSerializerOptions { WriteIndented = true }); Console.WriteLine(formattedJson);


0
投票
using System.Text.Json; namespace Something.Extensions; public static class StringExtensions { static JsonSerializerOptions defaultJsonSerializerOptions = new JsonSerializerOptions { WriteIndented = true }; public static string FormatJson(this string json, JsonSerializerOptions? options = default) => JsonSerializer.Serialize<object>(JsonSerializer.Deserialize<object>(json ?? "{}")!, options ?? defaultJsonSerializerOptions); }
用法

var r = @" { ""dsadsa"":""asdasd"" }"; content = r.FormatJson(new JsonSerializerOptions { WriteIndented = true });
用例示例:没有缩进响应的未知 API 响应

var businessId = 2; var request = new HttpRequestMessage(HttpMethod.Get, $"http://localhost:7010/Business/{businessId}"); var client = clientFactory.CreateClient(); var responseMessage = await client.SendAsync(request); if (responseMessage.IsSuccessStatusCode) { var r = await responseMessage.Content.ReadAsStringAsync(); content = r.FormatJson(new JsonSerializerOptions { WriteIndented = true }); } else { throw new Exception($"!IsSuccessStatusCode:{responseMessage.StatusCode}"); }
    

0
投票
.NET 9 中的序列化通过可定制的 JSON 输出提供了更大的灵活性。您现在可以轻松自定义缩进字符及其大小,以获得更具可读性的 JSON 文件。

var options = new JsonSerializerOptions { WriteIndented = true, IndentationSize = 4 }; string jsonString = JsonSerializer.Serialize(yourObject, options);
    
© www.soinside.com 2019 - 2024. All rights reserved.