c#json对象转数组,如何将包含数组的JSON对象转换为C#Dictionary< string,string&gt ;?...

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

client.PostAsync(baseAddress + path, new FormUrlEncodedContent(JsonConvert.DeserializeObject>(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 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?

解决方案

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.

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());

var result = JsonConvert.DeserializeObject>(jObject.ToString());

That way you will get result:

c5ba6d2587e2b540dd098a3de6ce7561.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值