1

I have this simple model in an ASP.NET WebAPI 2 application:

public class Model {
    public int ID { get; set; }
    public Dictionary<string, string> Dic { get; set; }
}

When it gets serialized, the output is:

{
    "ID": 0,
    "Dic": {
        "name1": "value1",
        "name2": "value2"
    }
}

I searched the problem, but it seems most people need this serialization:

{
    "ID": 0,
    "Dic": [{
        "Key": "name1",
        "Value": "value1"
    }]
}

And all solutions out there are resolving to that kind of serialization. But what I'm looking for is to serialize the dictionary into this format:

{
    "ID": 0,
    "Dic": [{
        "name1": "value1"
    }, {
        "name2": "value2"
    }]
}

In other words, I want to serialize it into an array of objects containing one "name1": "value1" pair each. Is there any way to do that? Or I should be looking for another type?

3
  • 1
    Array in json can't have key. You should use object (hash) instead. Commented Oct 26, 2016 at 8:29
  • 1
    Sorry man, your json is not valid. You can check it on any online json validator Commented Oct 26, 2016 at 8:50
  • See the update please Commented Oct 26, 2016 at 9:11

1 Answer 1

1

You can use a custom JsonConverter to get the JSON you're looking for. Here is the code you would need for the converter:

public class CustomDictionaryConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(IDictionary).IsAssignableFrom(objectType);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        IDictionary dict = (IDictionary)value;
        JArray array = new JArray();
        foreach (DictionaryEntry kvp in dict)
        {
            JObject obj = new JObject();
            obj.Add(kvp.Key.ToString(), kvp.Value != null ? JToken.FromObject(kvp.Value, serializer) : new JValue((string)null));
            array.Add(obj);
        }
        array.WriteTo(writer);
    }

    public override bool CanRead
    {
        get { return false; }
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

To use the converter, mark the dictionary in your model class with a [JsonConverter] attribute like this:

public class Model 
{
    public int ID { get; set; }
    [JsonConverter(typeof(CustomDictionaryConverter))]
    public Dictionary<string, string> Dic { get; set; }
}

Demo fiddle: https://dotnetfiddle.net/320LmU

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.