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

234 .net c# json javascriptserializer

我正在使用.NET JSON解析器,并希望序列化我的配置文件,以便它是可读的.所以代替:

{"blah":"v", "blah2":"v2"}
Run Code Online (Sandbox Code Playgroud)

我想要更好的东西:

{
    "blah":"v", 
    "blah2":"v2"
}
Run Code Online (Sandbox Code Playgroud)

我的代码是这样的:

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();
}
Run Code Online (Sandbox Code Playgroud)

Sky*_*ers 241

使用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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

结果

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

文档:序列化对象

  • @Brad他展示了完全相同的代码,但使用的是模型 (15认同)
  • 所以这个想法只是 Formatting.Indented (3认同)

dvd*_*dmn 160

Json.Net库的简短示例代码

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

  • 实际上,您可以更进一步并创建一个扩展方法;公开并将签名更改为 FormatJson(this string json) (2认同)

Dun*_*art 121

如果你有一个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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 仅仅为了美化Json字符串,这是一个比其他人更合适的解决方案...... (6认同)
  • 以下用例将失败:`JsonPrettify("null")`和`JsonPrettify("\"string \"")` (2认同)

ash*_*ber 89

用于美化现有JSON的最短版本:(编辑:使用JSON.net)

JToken.Parse("mystring").ToString()
Run Code Online (Sandbox Code Playgroud)

输入:

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

输出:

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

漂亮地打印一个对象:

JToken.FromObject(myObject).ToString()
Run Code Online (Sandbox Code Playgroud)

  • 即使事先不知道json的结构,这也可以工作.这是最短的答案. (3认同)
  • 啊,好的一点,谢谢.我已经更新了我的答案,使用`JToken`而不是`JObject`.这适用于对象或数组,因为`JToken`是`JObject`和`JArray`的祖先类. (3认同)
  • 这个优雅的答案应该被投票到顶部. (3认同)
  • 这有效,但前提是 json 对象不是数组。如果您知道它将是一个数组,您可以使用 JArray.Parse 代替。 (2认同)
  • 非常感谢,我浪费了大约 2 个小时来找到这个解决方案...无法想象没有 @stackoverflow 我的生活... (2认同)

Dar*_*usz 36

Oneliner使用Newtonsoft.Json.Linq:

string prettyJson = JToken.Parse(uglyJsonString).ToString(Formatting.Indented);
Run Code Online (Sandbox Code Playgroud)

  • 它位于 NewtonSoft.Json.Linq 命名空间中。我只知道这个,因为我也去寻找它。 (3认同)
  • 在Newtonsoft.Json中找不到此文件……也许我有一个旧版本。 (2认同)

Ebu*_*ube 31

所有这些都可以在一个简单的行中完成:

string jsonString = JsonConvert.SerializeObject(yourObject, Formatting.Indented);
Run Code Online (Sandbox Code Playgroud)

  • 请记住添加“使用 Newtonsoft.Json” (3认同)

Ome*_*r K 26

2023 更新

对于那些问我如何使用 C# 在 .NET 中获取格式化 JSON 并希望立即了解如何使用它的人以及单行爱好者。以下是缩进的 JSON 字符串一行代码:

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

Newtonsoft Json.Net版本:

using Newtonsoft.Json;

var jsonString = JsonConvert.SerializeObject(yourObj, Formatting.Indented);
Run Code Online (Sandbox Code Playgroud)

.Net 7版本:

using System.Text.Json;

var jsonString = JsonSerializer.Serialize(yourObj, new JsonSerializerOptions { WriteIndented = true });
Run Code Online (Sandbox Code Playgroud)

  • 这应该得到更多的支持。 (3认同)

And*_*erd 18

这是使用 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());
}
Run Code Online (Sandbox Code Playgroud)

  • 不错,不想添加额外的包。 (2认同)

Mak*_*man 11

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

JsonReaderWriterFactory.CreateJsonWriter(Stream stream,Encoding 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());
        }
    }
Run Code Online (Sandbox Code Playgroud)

注意线条

    var currentCulture = Thread.CurrentThread.CurrentCulture;
    Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
    ....
    Thread.CurrentThread.CurrentCulture = currentCulture;
Run Code Online (Sandbox Code Playgroud)

在具有不同区域设置的计算机上进行反序列化时,应使用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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

谢谢!


har*_*eyt 11

netcoreapp3.1

var js = JsonSerializer.Serialize(obj, new JsonSerializerOptions {
             WriteIndented = true
         });
Run Code Online (Sandbox Code Playgroud)

  • 这个答案应该有更多的票数。大家还在使用.Net Framework吗? (4认同)

Jam*_*son 8

使用System.Text.JsonJsonSerializerOptions.WriteIndented = true

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


Yol*_*ola 6

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