我试图在C#中序列化KeyValuePair属性,如下所示:
[JsonDisplayName("custom")]
public KeyValuePair<string,string> Custom { get; set; }
通过使用:设置属性到JSON
MyClass.Custom = new KeyValuePair<string, string>("destination", destination);
但我得到的输出看起来像这样:
"custom":{"Key":"destination","Value":"Paris"}
相反,我想:
"custom":{"destination":"Paris"}
任何想法如何?我使用Compact Framework和Visual Studio 2008,所以我不想使用任何外部库。非常感谢您的帮助。
更新 我必须使用我公司的Model类,它有一个SetCustom方法,如果我使用字典会引发异常。
答案 0 :(得分:1)
您可以使用词典而不是键值对
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));
}
}
这将产生
{"custom":{"destination1":"foo","destination2":"bar"}}
或者如果你想坚持KeyValuePair
,你需要创建自己的转换器
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));
}
}
答案 1 :(得分:0)
不要忘记从NuGet Newtonsoft.Json下载
class Program
{
static void Main(string[] args)
{
String [,] arr = new String[1,2];
arr[0,0] = "Hello";
arr[0,1] = "World";
Console.WriteLine(JsonConvert.SerializeObject(arr));
Console.ReadKey(true);
//[["Hello","World"]]
}
}