c# - Newtonsoft inline formatting for subelement while serializing -
is possible create attribute serialize subelements inline (formatting.none) newtonsoft json.net?
i have huge set of data , want keep readeable. subelements not important , can writen inline.
{ "name": "xxx", "desc": "xxx", "subelem": [ {"val1": 1, "val2": 2, ...}, //inline, {"val1": 1, "val2": 2, ...}, ... ] "subelem2": { "val1": 1, "val2": 2, ... } }
i want force inline serialization sub objects of models. in case, "subelem" items written inline. thanks
adding converter jsonconverterattribute
on class trickier because simplest implementation lead infinite recursion converter calls itself. it's necessary disable converter recursive calls in thread-safe manner, so:
public class noformattingconverter : jsonconverter { [threadstatic] static bool cannotwrite; // disables converter in thread-safe manner. bool cannotwrite { { return cannotwrite; } set { cannotwrite = value; } } public override bool canwrite { { return !cannotwrite; } } public override bool canread { { return false; } } public override bool canconvert(type objecttype) { throw new notimplementedexception(); // should applied property rather included in 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 // using disposable struct avoid overhead of allocating , freeing instance of finalizable class. public void dispose() { if (setvalue != null) setvalue(oldvalue); } #endregion }
and apply class (or property) 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)); } }
the output of test()
method above is:
{ "avalue": "a value", "nestedclass":{"values":["one","two","three"]}, "zvalue": "z value" }
Comments
Post a Comment