问题
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?
回答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
来源:https://stackoverflow.com/questions/40257262/serializing-dictionarystring-string-to-array-of-name-value