Serialize and Deserialize indexed field names to list

Viewed 59

I'm working with a Webservice that returns (and expects) some unusual formed JSON. Instead of using a list or an dictionary it uses a numbered field pattern:

{
    // some normal fields
    "col0" : "First column name",
    "val0" : "First value",
    "col1" : "Second column name",
    "val1" : "Second value",
    // ...
    "coln" : "n-th column name",
    "valn" : "n-th value"
} 

I want to serialize/deserialize theese values to/from a Dictionary<string, string> property using json.net.

1 Answers

json.net provides a mechanism to deserialize additional properties. To use it introduce a private property and mark it with the JsonExtensionDataAttribute to instruct the deserializer to store all properties, that cannot be mapped in theese dictionary. If the type is serialized, all values in this dictionary are also stored. To populate the extension dictionary resp. the public dictionary you can use the OnDeserialized resp. OnSerializing callbacks.

[JsonIgnore]
public Dictionary < string, string > Columns {get;} = new Dictionary <string, string>();

[JsonExtensionData()]
private Dictionary < string, JToken > _additionalData {get; set;}

[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
    int i = 0;
    while (_additionalData.TryGetValue($ "col{i}", out JToken column))
    {
        var value = _additionalData[$ "val{i}"];
        Columns.Add(column.ToObject < string > (), value.ToObject < string > ());
        i++;
    }
}

[OnSerializing]
private void OnSerializing(StreamingContext context)
{
    int i = 0;
    _additionalData = new Dictionary < string, JToken > ();
    foreach(var item in Columns)
    {
        _additionalData.Add($ "col{i}", item.Key);
        _additionalData.Add($ "val{i}", item.Value);
        i++;
    }
}
Related