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?CommentedAug 15, 2019 at 12:50
  • editted question
    – FllnAngl
    CommentedAug 15, 2019 at 12:51

3 Answers 3

1

Try doing:

strArray = js.Deserialize<string[]>("[\"false\",\"true\"]"); 
1
  • man, the only option I didnt test I assume.. thanks, I will accept as answer once I am allowed to
    – FllnAngl
    CommentedAug 15, 2019 at 12:56
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
  • js.Deserialize(..., typeof(T)) and jsDeserialize<T>(...) would behave the same, no?
    – Lukas
    CommentedAug 15, 2019 at 13:07
  • @Lukas Yes, they do.CommentedAug 15, 2019 at 13:08
  • 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
    – Lukas
    CommentedAug 15, 2019 at 13:09
  • 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>().CommentedAug 15, 2019 at 13:15
  • Ah, I see what you're saying. :-)
    – Lukas
    CommentedAug 15, 2019 at 13:16
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.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.