5

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?

2 Answers 2

7

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"}
0
4

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.