如何将包含数组的JSON对象转换为C#Dictionary <string,string>?

时间:2018-11-15 08:48:12

标签: c# asp.net-mvc winforms asp.net-web-api json.net

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

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

其中clientHttpClient类的对象。对于对WebApi的所有请求均执行此代码。我正在尝试将以下数据发送到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'

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

1 个答案:

答案 0 :(得分:2)

如果出于任何原因需要将所有值作为字符串发送,则必须先将字符串数组转换为字符串,然后再将其反序列化为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());

这样,您将获得结果:

enter image description here