Serialize Dictionary without property name with Newtonsoft.Json

跟風遠走 提交于 2019-12-10 15:24:44

问题


I'm using

var myResponse = new Response(myDictionary);
string response = JsonConvert.SerializeObject(myResponse);

where

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

    public Dictionary<string, string> MyDict { get; private set; }
}

I'm getting:

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

what I want to get is:

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

`

is that possible with Newtonsoft.Json?


回答1:


You're serializing the entire object. if you just want the output you specified then just serialize the dictionary:

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

this will output:

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



回答2:


If you want to work and serialize the entire class, and not the dictionary only, you can write a simple class which inherits JsonConverter which tells the serializer how to serialize the object:

[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);
    }
}

Now this:

void Main()
{
    var response = new Response();
    response.Foo = new Dictionary<string, string> { { "1", "1" }  };
    var json = JsonConvert.SerializeObject(response);
    Console.WriteLine(json);
}

Will output:

{ "1":"1" }

Although a bit verbose for such a simple task, but this will let you work with the object itself without worrying about serializing the dictionary only.



来源:https://stackoverflow.com/questions/32253259/serialize-dictionary-without-property-name-with-newtonsoft-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!