1

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"

2
  • 3
    What type is js? Commented Aug 15, 2019 at 12:50
  • editted question Commented Aug 15, 2019 at 12:51

3 Answers 3

1

Try doing:

strArray = js.Deserialize<string[]>("[\"false\",\"true\"]");
Sign up to request clarification or add additional context in comments.

1 Comment

man, the only option I didnt test I assume.. thanks, I will accept as answer once I am allowed to
1

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.

5 Comments

js.Deserialize(..., typeof(T)) and jsDeserialize<T>(...) would behave the same, no?
@Lukas Yes, they do.
Sorry, just a little confused about the 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
You will know when you need it :) It's hard to explain a real use case... but you can, for example, do something like js.Deserialize(..., someObject.GetType()) without knowing beforehand what type someObject is (you just know the JSON is the same type). You cannot do that with Deserialize<T>().
Ah, I see what you're saying. :-)
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.