Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

c#

json.net

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.

like image 914
Juan Carlos Oropeza Avatar asked Mar 12 '15 02:03

Juan Carlos Oropeza


2 Answers

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

like image 96
dvhh Avatar answered Oct 13 '22 19:10

dvhh


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
like image 42
Jeff Mercado Avatar answered Oct 13 '22 20:10

Jeff Mercado