I'm very new with JSON, please help!
I am trying to serialise a List<KeyValuePair<string, string>>
as JSON
Currently:
[{"Key":"MyKey 1","Value":"MyValue 1"},{"Key":"MyKey 2","Value":"MyValue 2"}]
Expected:
[{"MyKey 1":"MyValue 1"},{"MyKey 2":"MyValue 2"}]
I referred to some examples from this and this.
This is my KeyValuePairJsonConverter : JsonConverter
public class KeyValuePairJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
List<KeyValuePair<object, object>> list = value as List<KeyValuePair<object, object>>;
writer.WriteStartArray();
foreach (var item in list)
{
writer.WriteStartObject();
writer.WritePropertyName(item.Key.ToString());
writer.WriteValue(item.Value.ToString());
writer.WriteEndObject();
}
writer.WriteEndArray();
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(List<KeyValuePair<object, object>>);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var jsonObject = JObject.Load(reader);
var target = Create(objectType, jsonObject);
serializer.Populate(jsonObject.CreateReader(), target);
return target;
}
private object Create(Type objectType, JObject jsonObject)
{
if (FieldExists("Key", jsonObject))
{
return jsonObject["Key"].ToString();
}
if (FieldExists("Value", jsonObject))
{
return jsonObject["Value"].ToString();
}
return null;
}
private bool FieldExists(string fieldName, JObject jsonObject)
{
return jsonObject[fieldName] != null;
}
}
I am calling it from a WebService method like this
List<KeyValuePair<string, string>> valuesList = new List<KeyValuePair<string, string>>();
Dictionary<string, string> valuesDict = SomeDictionaryMethod();
foreach(KeyValuePair<string, string> keyValue in valuesDict)
{
valuesList.Add(keyValue);
}
JsonSerializerSettings jsonSettings = new JsonSerializerSettings { Converters = new [] {new KeyValuePairJsonConverter()} };
string valuesJson = JsonConvert.SerializeObject(valuesList, jsonSettings);
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…