如何将包含数组的JSON对象转换为C#Dictionary< string,string&gt ;? [英] How to convert a JSON object containing an array to C# Dictionary<string,string>?

查看:643
本文介绍了如何将包含数组的JSON对象转换为C#Dictionary< string,string&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码向WebAPI发送请求:

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

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

其中,clientHttpClient类的对象.对于对WebApi的所有请求都将执行此代码.我正在尝试将以下数据发送到API:

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
}

现在,因为FormUrlEncodedContent仅接受Dictionary<string,string>对象,所以我正在使用NewtonSoft的JSON.NET方法JsonConvert.DeserializeObject将此JSON转换为该类型.但是在sections数组开始的位置,它向我显示此错误消息: Unexpected character encountered while parsing value:[. Path 'sections'.

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'.

那么,如果我想对这种JSON数据使用相同的代码,该怎么办?

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

推荐答案

如果出于任何原因需要将所有值作为字符串发送,则必须先将字符串数组转换为字符串,然后再将其反序列化为Dictionary<string, string>.

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>.

可以这样做:

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

这样,您将获得结果:

这篇关于如何将包含数组的JSON对象转换为C#Dictionary&lt; string,string&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆