Juan Carlos Oropeza
Juan Carlos Oropeza

Reputation: 48207

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

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.

Upvotes: 7

Views: 8676

Answers (2)

Jeff Mercado
Jeff Mercado

Reputation: 134621

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

Upvotes: 2

dvhh
dvhh

Reputation: 4750

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

Upvotes: 4

Related Questions