簡體   English   中英

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

[英]How do I get formatted JSON in .NET using C#?

我正在使用 .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.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"
}

文檔: 序列化對象

Json.Net 庫的較短示例代碼

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

如果您有一個 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();
        }
    }
}

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

Oneliner 使用Newtonsoft.Json.Linq

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

所有這些都可以在一個簡單的行中完成:

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

這是使用 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());
}

您可以使用以下標准方法獲取格式化的 Json

JsonReaderWriterFactory.CreateJsonWriter(Stream stream, Encoding encoding, bool ownsStream, bool indent, string indentChars)

只設置“縮進==真”

嘗試這樣的事情

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

謝謝!

netcoreapp3.1

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

使用System.Text.Json設置JsonSerializerOptions.WriteIndented = true

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

2023年更新

對於那些問我如何使用 C# 將 JSON 格式化為 .NET 並想立即查看如何使用它的人和在線愛好者 以下是縮進的 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 });

首先我想在 Duncan Smart 帖子下添加評論,但不幸的是我還沒有足夠的聲譽來發表評論。 所以我會在這里嘗試。

我只想警告副作用。

JsonTextReader 在內部將 json 解析為類型化的 JToken,然后將它們序列化回來。

例如,如果您的原始 JSON 是

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

美化后你得到

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

當然兩個json字符串是等價的,會反序列化為結構上相等的對象,但是如果你需要保留原始字符串值,你需要考慮到這一點

這對我有用。 如果有人正在尋找 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

我有一些非常簡單的東西。 您可以將任何要轉換為 json 格式的對象作為輸入:

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

下面的代碼對我有用:

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

對於使用 .NET Core 3.1 的 UTF8 編碼的 JSON 文件,我終於能夠根據來自 Microsoft 的這些信息使用 JsonDocument: https ://docs.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();

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM