How do I deserialize a JSON array that contains only values?

一个人想着一个人 提交于 2019-12-07 06:35:02

问题


I'm getting this result from a web function.

["767,20150221122715,121053103,14573465,1,7,302",
"767,20150221122756,121053165,14573375,1,0,302",
"767,20150221122840,121053498,14572841,1,12,124"]

Usually Json have PropertyName: Value But this have an array of strings, and each string have the values separated by comma. I know what each value position mean.

I try using JsonConvert.DeserializeObject but couldn't make it work.

string deserializedProduct = JsonConvert.DeserializeObject<string>(json);
//and
List<string> deserializedProduct = JsonConvert.DeserializeObject<string>(json);

I can parse the string doing a split, but I'm wondering if there is an easy way.


回答1:


To answer your question, according to to http://json.org/, it is a valid JSON value (an array of string).

To deserialize it according to this stack overflow question you should use JsonConvert.DeserializeObject<List<string>>(json); to convert it




回答2:


The generic parameter to the DeserializeObject<T>() method is the type you want the deserializer to deserialize to. Your json string represents an array of strings so you should be deserializing to a collection of strings (typically List<string>).

var values = JsonConvert.DeserializeObject<List<string>>(json);

However, it isn't necessary to specify the type. There is a non-generic overload that returns object. It will (in this case) return an instance of a JArray with the appropriate values.

object values = JsonConvert.Deserialize(json);

Though, it would be better to return a more specific type if possible. To keep it more generalized, you can use JToken for the generic type or even more specifically, JArray.

var values = JsonConvert.Deserialize<JToken>(json); // good
var values = JsonConvert.Deserialize<JArray>(json); // better in this case


来源:https://stackoverflow.com/questions/29001023/how-do-i-deserialize-a-json-array-that-contains-only-values

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