How to convert a JSON object containing an array to C# Dictionary<string,string>?

萝らか妹 提交于 2020-01-15 09:47:27

问题


I am sending a request to a WebAPI using following code:

client.PostAsync(baseAddress + path, new FormUrlEncodedContent(JsonConvert.DeserializeObject<Dictionary<string,string>>(form)))

where client is an object of HttpClient class. This code is executed for all the requests to the WebApi. I am trying to send following data to the API:

{
    "code":"GUEST",
    "category":"Indian",
    "sections":["01000000-0000-0000-0000-000000000000","02000000-0000-0000-0000-000000000000"],
    "date":"0001-01-01T00:00:00",
    "time":"0001-01-01T00:00:00",
    "quantity":1.0,
    "price":0.0,
    "discount":0.0,
    "paymentMethod":"ID",
    "paymentMethodID":null,
    "ticketNo":null
}

Now because the FormUrlEncodedContent accepts only the Dictionary<string,string> object, I am converting this JSON into that type using NewtonSoft's JSON.NET method JsonConvert.DeserializeObject. But at the point where sections array starts, it is showing me this error message: Unexpected character encountered while parsing value:[. Path 'sections'.

So, what approach should I follow if I want to use the same code for this kind of JSON data?


回答1:


If you for any reason need to send all values as strings, then you must convert array of strings to string before deserializing it to Dictionary<string, string>.

It can be done like this:

var json = "{\"code\":\"GUEST\",\"category\":\"Indian\",\"sections\":[\"01000000-0000-0000-0000-000000000000\",\"02000000-0000-0000-0000-000000000000\"],\"date\":\"0001-01-01T00:00:00\",\"time\":\"0001-01-01T00:00:00\",\"quantity\":1.0,\"price\":0.0,\"discount\":0.0,\"paymentMethod\":\"ID\",\"paymentMethodID\":null,\"ticketNo\":null}";

var jObject = JObject.Parse(json);
jObject["sections"] = JsonConvert.SerializeObject(jObject["sections"].ToObject<string[]>());

var result = JsonConvert.DeserializeObject<Dictionary<string, string>>(jObject.ToString());

That way you will get result:



来源:https://stackoverflow.com/questions/53315488/how-to-convert-a-json-object-containing-an-array-to-c-sharp-dictionarystring-st

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!