Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize Dictionary without property name with Newtonsoft.Json

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?

like image 482
Dan Dinu Avatar asked Dec 20 '22 00:12

Dan Dinu


1 Answers

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"}
like image 99
Nasreddine Avatar answered Dec 28 '22 23:12

Nasreddine