使用Newtonsoft.Json序列化不带属性名称的Dictionary

Dan*_*inu 4 .net c# serialization json json.net

我正在使用

var myResponse = new Response(myDictionary);
string response = JsonConvert.SerializeObject(myResponse);
Run Code Online (Sandbox Code Playgroud)

哪里

internal class Response 
{
    public Response (Dictionary<string, string> myDict) 
    {
        MyDict = myDict;
    }

    public Dictionary<string, string> MyDict { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)

我越来越:

{
  "MyDict": 
  { 
     "key" : "value", 
     "key2" : "value2"
  }
}
Run Code Online (Sandbox Code Playgroud)

我想得到的是:

{
    "key" : "value", 
    "key2" : "value2"
}
Run Code Online (Sandbox Code Playgroud)

`

是不是可能与Newtonsoft.Json?

Nas*_*ine 6

您正在序列化整个对象.如果你只想要你指定的输出,那么只需序列化字典:

string response = JsonConvert.SerializeObject(myResponse.MyDict);
Run Code Online (Sandbox Code Playgroud)

这将输出:

{"key":"value","key2":"value2"}
Run Code Online (Sandbox Code Playgroud)