Customizing Json.NET serialization: turning object into array to avoid repetition of property names

前端 未结 6 1634
半阙折子戏
半阙折子戏 2020-12-30 00:11

I\'m sending large amounts of different JSON graphs from a server to a client (I control both) and they all contain a pathological case: a large array of homogeneous (same t

6条回答
  •  独厮守ぢ
    2020-12-30 00:39

    A big strength of the popular JSON serialization libraries (not to say the whole idea behind JSON) is to take language features - objects, arrays, literals - and serialize them into an equivalent JSON representation. You can look at an object structure in C# (e.g.) and you know what the JSON will look like. This is not the case if you start changing the whole serialization mechanism. *)

    Apart from DoXicK's suggestion to use gzip for compression, if you really want to define a different JSON format, why not simply transform your object tree in C# before serializing it?

    Something like

    var input = new[]
        {
            new { Key1 = 87, Key2 = 99 },
            new { Key1 = 42, Key2 = -8 }
        };
    
    
    var json = JSON.Serialize(Transform(input));
    
    
    object Transform(object[] input)
    {
        var props = input.GetProperties().ToArray();
        var keys = new[] { "$" }.Concat(props.Select(p => p.Name));
        var stripped = input.Select(o => props.Select(p => p.GetValue(o)).ToArray();
        return keys.Concat(stripped);
    }
    

    would do. This way you will not confuse any programmers by changing the way JSON works. Instead the transformation will be an explicit pre-/postprocessing step.


    *) I would even argue that it is like a protocol: Object is { }, array is [ ]. It is, as the name says, a serialization of your object structure. If you change the serialization mechanism, you change the protocol. Once you do that, you don't need to look it like JSON any longer at all, because the JSON does not properly represent your object structure anyway. Calling it JSON and making it look like such has the potential to confuse each of your fellow/future programmers as well as yourself when you re-visit your code later.

提交回复
热议问题