Reputation: 72
I have a string with an array of Json inside
"[{'firstname':'john','lastname':'doe'},{'firstname':'mary','lastname':'jane'}]"
How do I convert that to a string array of json?
For example the above would be
["{'firstname':'john','lastname':'doe'}","{'firstname':'mary','lastname':'jane'}"]
I then can use JObject.Parse on each of the elements of the array to make JObjects from the json.
Upvotes: 1
Views: 140
Reputation: 2803
You mention JObject.Parse
, so you're using Json.NET, right? Do you really need the intermediate array of strings? If not, just use JArray.Parse
to parse the JSON in one go.
If the elements in the array all represent the same type and you want to convert them, you could convert them all into a strongly typed array using Values<T>()
:
Person[] people = JArray.Parse(json).Values<Person>().ToArray();
Upvotes: 3
Reputation: 4276
string jsonString = "[{'firstname':'john','lastname':'doe'},{'firstname':'mary','lastname':'jane'}]";
string[] jsonStringArray = JsonConvert.DeserializeObject<JArray>(jsonString)
.Select(JsonConvert.SerializeObject)
.ToArray();
Alternatively, you can do this:
class Person
{
public string firstname { get; set; }
public string lastname { get; set; }
}
...
string jsonString = "[{'firstname':'john','lastname':'doe'},{'firstname':'mary','lastname':'jane'}]";
Person[] personArray = JsonConvert.DeserializeObject<Person[]>(jsonString);
Upvotes: 0
Reputation: 22631
Assuming your JSON is in a string variable json
, the shortest way to get an array of JSON string is:
JArray.Parse(json).Select(o => JsonConvert.SerializeObject(o)).ToArray();
However, the quickest way to get the JObject
s is
foreach (JObject jObject in JArray.Parse(json)) {
// do something with jObject
}
Upvotes: 1