2

I am trying to create the following JSON result in my code (C#) as this is how the API that I am using would want the JSON to be, but not able to create it exactly, hence which is why the API returns with errors.

End result:

{
  "reportKey" : {
     "key" : "552d20ce-1269-4cb4-a679-0cd51d3e2058"
  }
}

In my code, I have

var reportKey = new KeyValuePair<string, string>("key", reportId);
var requestJson = new { reportKey };

When I look up the JSON value by serializing this requestJson using the JsonConvert, it comes up as

{ reportKey : { key : "key", value : "CBHJ1234" } } 

Not the way I want it up above.

Any ideas on what I could be doing wrong? I probably don't want to use KeyValuePair here, do I?

Nkosi
  • 235,767
  • 35
  • 427
  • 472
bladerunner
  • 597
  • 2
  • 7
  • 21

1 Answers1

4

Ironically, a KeyValuePair, when serialised to JSON, creates two key value pairs because it has two properties Key and Value.

The easiest way to do this is to not use KeyValuePair, and just create an anonymous class yourself:

var objectToSerialise = new {
    reportKey = new {
        key = reportId
    }
};

var json = JsonConvert.SerializeObject(objectToSerialise);
Sweeper
  • 213,210
  • 22
  • 193
  • 313