【问题标题】:Serialize Dictionary without property name with Newtonsoft.Json使用 Newtonsoft.Json 序列化没有属性名称的字典
【发布时间】:2015-08-27 15:16: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 有可能吗?

【问题讨论】:

    标签: c# .net json serialization json.net


    【解决方案1】:

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

    string response = JsonConvert.SerializeObject(myResponse.MyDict);
    

    这将输出:

    {"key":"value","key2":"value2"}
    

    【讨论】:

      【解决方案2】:

      如果您想处理和序列化整个类,而不仅仅是字典,您可以编写一个继承 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" }
      

      虽然对于这样一个简单的任务有点冗长,但这会让您使用对象本身而不必担心只序列化字典。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-15
        • 1970-01-01
        相关资源
        最近更新 更多