How can I implement custom serialisation of json appending the types to the property names?

Viewed 113

I am trying to serialize an object to JSON using newtonsoft.json. The only thing is that I cannot append the json type to the field name. Consider this example:

var item = new {
    value = "value",
    data = new []{"str", "str"},
    b = true
};

I want to convert that to

{
    "value.string" : "value",
    "data.array" : ["str", "str"],
    "b.bool" : true
}

or something similar. The idea is to append the json type (not the c# type) to the json field. The reason I don't want to append the C# type is because it could be complex (sometimes the type is anonymous, sometimes it is IEnumerable, etc.)

I have seen many solutions that can convert to C# type such as implementing a IContractResolver. Unfortunately that doesn't work for this case.

I also do not know the type that I will convert before hand.

The closest I could get to is

public JObject Convert(JObject data)
{
    var queue = new Queue<JToken>();

    foreach (var child in data.Children())
    {
        queue.Enqueue(child);
    }

    while (queue.Count > 0)
    {
        var token = queue.Dequeue();

        if (token is JProperty p)
        {
            if (p.Value.Type != JTokenType.Object)
            {
                token.Replace(new JProperty(
                    $"{p.Name}.{p.Value.Type}",
                    p.Value
                ));
            }
        }

        foreach (var child in token.Children())
        {
            queue.Enqueue(child);
        }
    }

    return data;
}

But it does not work for nested objects like

var result = convertor.Convert(JObject.FromObject(new { nested = new { item = "str"}}));

For some reason, Replace does not work for the nested objects. Not sure if it is a bug or not.

1 Answers
Related