Mr Lord
Mr Lord

Reputation: 150

Convert Simple json Array to string Array In C#

I have a string contain a json array.

The array look like this:

[item1, item2, item3]

I need a c# function to convert this json to string[]

I couldn't find any example/tutorial for this.

Upvotes: 1

Views: 6785

Answers (1)

Shyju
Shyju

Reputation: 218702

If your string variable is the string representation of an array like

"['item1', 'item2', 'item3']"

Then you can deserialize it using one of the serializers. Here is one example using JSON.NET

var a = "['item1', 'item2', 'item3']";
string[] resultArray = Newtonsoft.Json.JsonConvert.DeserializeObject<string[]>(a);

The string [item1, item2, item3] does not look like the stringified version of an array and cannot be easily converted to an array like we did above, as it is.

If your string variable value is something like item1, item2, item3, you can call string.Split method which will give you an array.

var a = "item1, item2, item3";
string[] resultArray = a.Split(',');

Upvotes: 4

Related Questions