将字典序列化为json

时间:2017-08-24 16:08:15

标签: c# json serialization json.net restsharp

我有任何方法:

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

请求是RestSharp.RestRequest,ticketsInfo是一个值为

的字典
Key:12041, Value:1
Key:12040, Value:2

命令&#34; AddJsonBody&#34;我有request.Parameters 1参数

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

但我需要

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

我如何得到正确的?

1 个答案:

答案 0 :(得分:0)

那么,实现AddJsonBody方法序列化的问题。当我通过句柄序列化对象然后通过句柄添加正文请求 - 一切都是正确的:

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