简体   繁体   中英

Serialize dictionary to json

I Have any method:

IExternalResponse<ReserveResponse> ReserveFreePlacement(IDictionary<int,int> ticketsInfo) {
    var request = new RestRequest("", Method.POST);
    request.AddJsonBody(
        new
        {
            command = "RESERVATION",
            categoryQuantityMap = JsonConvert.SerializeObject(ticketsInfo),
        });
    return GetResult<ReserveResponse>(request, RestClient, "Reservation"); }

request is RestSharp.RestRequest , ticketsInfo is a dictionary with a values:

Key:12041, Value:1
Key:12040, Value:2

After command "AddJsonBody" i have in request.Parameters 1 parameter

application/json={
  "command": "RESERVATION",
  "categoryQuantityMap": "{\"12041\":1,\"12040\":1}",
  "versionCode": "1.0"
} 

but i need

application/json={
  "command": "RESERVATION",
  "categoryQuantityMap": {
    "12041":1,
    "12040":2
    },
  "versionCode": "1.0"
}

How do i get the right one?

So, the problem in implementing method serialization of AddJsonBody. When i by handle serialize object then by handle add body request - everything is correct:

IExternalResponse<ReserveResponse> ReserveFreePlacement(IDictionary<int,int> ticketsInfo) 
{
    var jsonBody = JsonConvert.SerializeObject( new
    {
        command = "RESERVATION",
        categoryQuantityMap = ticketsInfo,
        versionCode = "1.0"
    });
    var request = new RestRequest("", Method.POST);
    request.AddParameter("application/json", jsonBody, ParameterType.RequestBody);
    return GetResult<ReserveResponse>(request, RestClient, "Reservation");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM