Home > Net >  ServiceStack: How do I Serialize a nested object of Dictionary<string, object>?
ServiceStack: How do I Serialize a nested object of Dictionary<string, object>?

Time:07-02

"event-data":
    {
        "event": "opened",
        "timestamp": 1529006854.329574,
        "id": "DACSsAdVSeGpLid7TN03WA",
        "delivery-status": {
            "title": "success"
        }
    }
//Structure
public List<Dictionary<string, object>> EventData { get; set; } = new List<Dictionary<string, object>>();
var json = ServiceStack.Text.JsonSerializer.SerializeToString(request.EventData);

So clearly this Jsonifies the object, but only at the root level. Every child object becomes riddled with \n and \t escapes... so it's just flat stringing the children.

What's the proper (Fastest) way to make this just raw nested Json?

CodePudding user response:

You can use the late-bound generic Dictionary<string, object> and List<object>, e.g:

var obj = new Dictionary<string, object> {
    ["event-data"] = new Dictionary<string, object> {
        ["event"] = "opened",
        ["timestamp"] = 1529006854.329574,
        ["id"] = "DACSsAdVSeGpLid7TN03WA",
        ["delivery-status"] = new Dictionary<string,object> {
            ["title"] = "success"
        }
    }
};
obj.ToJson().IndentJson().Print();

Prints out:

{
    "event-data": {
        "event": "opened",
        "timestamp": 1529006854.329574,
        "id": "DACSsAdVSeGpLid7TN03WA",
        "delivery-status": {
            "title": "success"
        }
    }
}

When in doubt, you can use JS Utils to parse any arbitrary JSON which will parse them in late-bound generic collections:

var dto = JSON.parse(json);
dto.ToJson().IndentJson().Print();

Note: JS Utils is better at deserializing unknown JSON whilst ServiceStack.Text JSON Serializer is better about deserializing into typed POCOs.

  • Related