使用Newtonsoft.Json序列化没有属性名的字典
本文关键字:属性 字典 Newtonsoft Json 序列化 使用 | 更新日期: 2023-09-27 18:10:02
我用
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?
您正在序列化整个对象。如果您只想要指定的输出,那么只需序列化字典:
string response = JsonConvert.SerializeObject(myResponse.MyDict);
这将输出:
{"key":"value","key2":"value2"}
如果你想序列化整个类,而不仅仅是字典,你可以写一个继承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" }
虽然对于这样一个简单的任务来说有点冗长,但这将使您可以处理对象本身,而不必担心只序列化字典。