简体   繁体   中英

convert json string to string array

I'm trying to convert a json string to a string array

my json string: "[\\"false\\",\\"true\\"]"

var js = new System.Web.Script.Serialization.JavaScriptSerializer();
string[] strArray = new string[2];
strArray = js.Deserialize("[\"false\",\"true\"]", string[2]).ToArray();

but it only allows me to do a charArray.

I just need to be able to call my result as strArray[0] so that it will return "false"

尝试做:

strArray = js.Deserialize<string[]>("[\"false\",\"true\"]");

Your example code wouldn't compile. The second parameter should be a Type object, which string[2] isn't. It should be this:

strArray = js.Deserialize("[\"false\",\"true\"]", typeof(string[]));

Or, as the other answer mentioned, you can use the other, generic overload for the method:

strArray = js.Deserialize<string[]>("[\"false\",\"true\"]");

Either one will do exactly the same thing. It's just handy to be able to pass a Type object sometimes if you don't know beforehand what the actual type will be. In this case you do, so it doesn't matter.

Why not use Newtonsoft's JArray type? It is built for this conversion and can handle many edge cases automatically.

var jArray = JArray.Parse("[\"false\",\"true\"]");
var strArray = jArray.ToObject<string[]>()

This will give you a string array. But you could also elect to use .ToArray() to convert to a JToken array which can sometimes be more useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM