2017-08-24 108 views
0

我有任何方法:序列化字典JSON

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 

命令 「AddJsonBody」 i之後具有在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" 
} 

我如何得到正確的?

+0

您的'categoryQuantityMap'具有哪種類型?如果它是一個字符串,那麼它將被轉義。你可以輸入你的'categoryQuantityMap'到實際的數據嗎? –

+0

'categoryQuantityMap = JsonConvert.SerializeObject(ticketsInfo)''只是將字典轉換爲JSON字符串。你嘗試過'categoryQuantityMap = ticketsInfo'嗎? – crashmstr

+0

我可以更改類型ticketsInfo以獲得期望的結果 –

回答

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