c# - DataContractJsonSerializer 人类可读的 json

标签 c# json datacontractjsonserializer

<分区>

基本上是 this 的骗局有一个显着差异的问题 - 我必须使用 DataContractJsonSerializer

一个简单的

using (var stream = new MemoryStream())
{
    var serializer = new DataContractJsonSerializer(typeof(Person));
    serializer.WriteObject(stream, obj);
    ...
    return stream.ToArray();
}

生成单行 json,例如(保存在文件中时)

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

制作它的选项有哪些

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

我可以想到后处理...有更简单的选择吗?例如。类似于格式化 xml produced by DataContractSerializer

using (var stream = new MemoryStream())
{
    var serializer = new DataContractJsonSerializer(typeof(T));
    // "beautify"
    using (var writer = new SomeKindOfWriter(stream))
        serializer.WriteObject(writer, obj);
    ...
    return stream.ToArray();
}

有没有办法让这样的SomeKindOfWriter在需要的时候美化json?

最佳答案

https://stackoverflow.com/a/38538454/6627992

您可以使用以下标准方法获取格式化的 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 来避免在具有不同区域设置的计算机上反序列化期间出现异常。例如,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);
        }
    }

谢谢!

关于c# - DataContractJsonSerializer 人类可读的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33371606/

相关文章:

c# 使用 AngleSharp 解析 HTML,找到带有部分 ID 的 DIV

javascript - 在 Angular 项目中迭代 JSON 响应以创建我可以在应用程序中使用的新 $scope 对象

c# - 在 Windows Phone 上将 json 反序列化为对象 c#

c# - 为什么我不能序列化具有私有(private) setter 的属性(C#、json)

c# - 如何在 INSERT 上将 BLOB 流式传输到 VARBINARY(MAX)

c# - 如何配置 owin/Katana 以监听所有主机 ip 地址

c# - 我应该使用字节还是整数?

java - 使用 com.fasterxml.jackson.databind.ObjectMapper 序列化接口(interface)字段

mysql - 如果包含 json 文档作为字符串,如何从 MySQL(5.6) 列中获取值

c# - 反序列化 RD.Details 类型的对象时出错。 '�19.95 Per Person' 包含无效的 UTF8 字节