我正在使用
var myResponse = new Response(myDictionary);
string response = JsonConvert.SerializeObject(myResponse);
,其中
internal class Response
{
public Response (Dictionary<string, string> myDict)
{
MyDict = myDict;
}
public Dictionary<string, string> MyDict { get; private set; }
}
我得到了:
{
"MyDict":
{
"key" : "value",
"key2" : "value2"
}
}
我想得到的是:
{
"key" : "value",
"key2" : "value2"
}
`
可以使用Newtonsoft.Json吗?
答案 0 :(得分:5)
您正在序列化整个对象。如果你只想要你指定的输出,那么只需序列化字典:
string response = JsonConvert.SerializeObject(myResponse.MyDict);
这将输出:
{"key":"value","key2":"value2"}
答案 1 :(得分:4)
如果你想工作和序列化整个类,而不只是字典,你可以编写一个继承JsonConverter
的简单类,告诉序列化器如何序列化对象:
[JsonConverter(typeof(ResponseConverter))]
public class Response
{
public Dictionary<string, string> Foo { get; set; }
}
public class ResponseConverter : JsonConverter
{
public override object ReadJson(
JsonReader jsonReader, Type type, object obj, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(
JsonWriter jsonWriter, object obj, JsonSerializer serializer)
{
var response = (Response)obj;
foreach (var kvp in response.Foo)
{
jsonWriter.WritePropertyName(kvp.Key);
jsonWriter.WriteValue(kvp.Value);
}
}
public override bool CanConvert(Type t)
{
return t == typeof(Response);
}
}
现在这个:
void Main()
{
var response = new Response();
response.Foo = new Dictionary<string, string> { { "1", "1" } };
var json = JsonConvert.SerializeObject(response);
Console.WriteLine(json);
}
将输出:
{ "1":"1" }
虽然对于这样一个简单的任务有点冗长,但这样可以让你使用对象本身,而不用担心只是序列化字典。