How to properly serialize my object that contains

2019-08-01 00:06发布

问题:

I'm trying to serialize a collection of object named TableDTO. This object contains a Name, Date and a List>. I'm trying to serialize it using Newtonsoft.Json library in C#

Every things works good when i construct the object. I add the KeyValuePair like this :
mylist.Add(new KeyValuePair<string, string>($"Col{compteur}", value.Value));
Then i add the list to my TableDTO
TableDTO.List = mylist
Then i serialize my object like this
JsonConvert.SerializeObject(TableDto);
And here is what i got

{ "FileName" : "MEP_3_10$3aList.xlsx", "Conditions" :{"Predicate" : "<select a condition>"}, "DataRows" : [{"Key" : "Col1","Value" : "value"}, {"Key" : "Col2","Value" : "value"}] }

The problem I encountered is when i serialized it Instead of having

{
    {"Col1":"value"},
    {"Col2":"value"}
}

The list is serialized like this

{
    {"Key" : "Col1","Value" : "value"},
    {"Key" : "Col2","Value" : "value"}
}

I tried to use a converter as described on another post in stackoverflow but since the list is a property of my object it's not as easy.

Thanks a lot for your help

回答1:

The problem you encounter is: NewtonSoft JSON can't handle dictionary key values and struct.

Please inspect my code:

public class CustomJSONSerializationHelper
{
    public string CustomSerialize(Dictionary<AuthorizationKey, ConditionalActionFlags> actionFlagMappings)
    {
        // ToArray() and use custom convertors, because NewtonSoft JSON can't handle dictionary key values and struct.
        var jsonString = JsonConvert.SerializeObject(actionFlagMappings.ToArray(), new Newtonsoft.Json.Converters.StringEnumConverter(), new AuthorizationKeyJsonConverter());
        return jsonString;
    }

    public Dictionary<AuthorizationKey, ConditionalActionFlags> CustomDeserialize(string jsonActionFlagMappings)
    {
        var resultArray = CustomDeserializeOverLoad(jsonActionFlagMappings);
        return (resultArray != null) ? resultArray.ToList().ToDictionary(pair => pair.Key, pair => pair.Value) : null;
    }

    public KeyValuePair<AuthorizationKey, ConditionalActionFlags>[] CustomDeserializeOverLoad(string jsonActionFlagMappings)
    {
        var result = JsonConvert.DeserializeObject<KeyValuePair<AuthorizationKey, ConditionalActionFlags>[]>(jsonActionFlagMappings,
             new Newtonsoft.Json.Converters.StringEnumConverter(), new AuthorizationKeyJsonConverter());
        return result;
    }
}

I call it like this:

    private string ObjectToJSON(Dictionary<AuthorizationKey, ConditionalActionFlags> actionFlagsMapping)
    {
        CustomJSONSerializationHelper customSerializationHelper = new CustomJSONSerializationHelper();
        return customSerializationHelper.CustomSerialize(actionFlagsMapping);
    }