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

走远了吗. 提交于 2019-12-05 11:41:11
dvhh

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

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