I'm trying to serialize a KeyValuePair property in C# that looks like this:
[JsonDisplayName("custom")]
public KeyValuePair<string,string> Custom { get; set; }
to JSON by setting the property with:
MyClass.Custom = new KeyValuePair<string, string>("destination", destination);
But the output I get looks something like this:
"custom":{"Key":"destination","Value":"Paris"}
Instead I want:
"custom":{"destination":"Paris"}
Any ideas how? I'm using Compact Framework and Visual Studio 2008 so I prefer not to use any external library. You're help is greatly appreciated.
Update: I have to use my company's Model class which has a SetCustom method that throws an exception if I use a dictionary.
You can use dictionary instead of key value pair
public class A
{
[JsonProperty("custom")]
public Dictionary<string, string> Custom
{
get;
set;
}
}
public class Program
{
public static void Main()
{
A custom = new A();
custom.Custom = new Dictionary<string, string>(){
{"destination1", "foo"},
{"destination2", "bar"},
};
Console.WriteLine(JsonConvert.SerializeObject(custom));
}
}
This will produce
{"custom":{"destination1":"foo","destination2":"bar"}}
Or if you want to stick with KeyValuePair you will need to create your own converter
public class A
{
[JsonProperty("custom")]
public KeyValuePair<string, string> Custom
{
get;
set;
}
}
class KeyValueStringPairConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
KeyValuePair<string, string> item = (KeyValuePair<string, string>)value;
writer.WriteStartObject();
writer.WritePropertyName(item.Key);
writer.WriteValue(item.Value);
writer.WriteEndObject();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof (KeyValuePair<string, string>);
}
}
public class Program
{
public static void Main()
{
A custom = new A();
JsonSerializerSettings settings = new JsonSerializerSettings{Converters = new[]{new KeyValueStringPairConverter()}};
custom.Custom = new KeyValuePair<string, string>("destination", "foo");
Console.WriteLine(JsonConvert.SerializeObject(custom, settings));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With