序列化时Newtonsoft内联格式用于子元素

序列化时Newtonsoft内联格式用于子元素

本文介绍了序列化时Newtonsoft内联格式用于子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建一个属性以使用newtonsoft json.net内联化一些子元素(Formatting.None)?

Is it possible to create an attribute to serialize some subelements inline (Formatting.None) with newtonsoft json.net?

我有一组非常庞大的数据,我想保持其可读性.某些子元素不是很重要,可以内联编写.

I have a very huge set of data and I want to keep it readeable.Some subelements are not very important and can be writen inline.

{
    "name": "xxx",
    "desc": "xxx",
    "subelem": [
        {"val1": 1, "val2": 2, ...}, //inline,
        {"val1": 1, "val2": 2, ...},
        ...
    ]
    "subelem2": {
        "val1": 1,
        "val2": 2,
        ...
    }
}

我想对模型的某些子对象强制进行内联序列化.在这种情况下,"subelem"项目将内联写入.谢谢

I want to force the inline serialization for some sub objects of my models.In this case, "subelem" items will be written inline.Thanks

推荐答案

将转换器添加为 JsonConverterAttribute 比较棘手,因为最简单的实现会在转换器调用自身时导致无限递归.因此,有必要以线程安全的方式禁用递归调用的转换器,如下所示:

Adding the converter as a JsonConverterAttribute on a class is trickier because the simplest implementation will lead to an infinite recursion as the converter calls itself. Thus it's necessary to disable the converter for recursive calls in a thread-safe manner, like so:

public class NoFormattingConverter : JsonConverter
{
    [ThreadStatic]
    static bool cannotWrite;

    // Disables the converter in a thread-safe manner.
    bool CannotWrite { get { return cannotWrite; } set { cannotWrite = value; } }

    public override bool CanWrite { get { return !CannotWrite; } }

    public override bool CanRead { get { return false; } }

    public override bool CanConvert(Type objectType)
    {
        throw new NotImplementedException(); // Should be applied as a property rather than included in the JsonSerializerSettings.Converters list.
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        using (new PushValue<bool>(true, () => CannotWrite, val => CannotWrite = val))
        using (new PushValue<Formatting>(Formatting.None, () => writer.Formatting, val => writer.Formatting = val))
        {
            serializer.Serialize(writer, value);
        }
    }
}

public struct PushValue<T> : IDisposable
{
    Action<T> setValue;
    T oldValue;

    public PushValue(T value, Func<T> getValue, Action<T> setValue)
    {
        if (getValue == null || setValue == null)
            throw new ArgumentNullException();
        this.setValue = setValue;
        this.oldValue = getValue();
        setValue(value);
    }

    #region IDisposable Members

    // By using a disposable struct we avoid the overhead of allocating and freeing an instance of a finalizable class.
    public void Dispose()
    {
        if (setValue != null)
            setValue(oldValue);
    }

    #endregion
}

然后将其应用于类(或属性),如下所示:

And then apply it to a class (or property) like so:

[JsonConverter(typeof(NoFormattingConverter))]
public class NestedClass
{
    public string[] Values { get; set; }
}

public class TestClass
{
    public string AValue { get; set; }

    public NestedClass NestedClass { get; set; }

    public string ZValue { get; set; }

    public static void Test()
    {
        var test = new TestClass { AValue = "A Value", NestedClass = new NestedClass { Values = new[] { "one", "two", "three" } }, ZValue = "Z Value" };
        Debug.WriteLine(JsonConvert.SerializeObject(test, Formatting.Indented));
    }
}

上面的Test()方法的输出是:

{
  "AValue": "A Value",
  "NestedClass":{"Values":["one","two","three"]},
  "ZValue": "Z Value"
}

这篇关于序列化时Newtonsoft内联格式用于子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 06:34