1

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.

7
  • Split he Stroug by the characters. Commented Jul 24, 2015 at 19:23
  • So that first string is your json? Or is a string inside you json? It's not really clear. If it is you json you should be able to deserailize it to an array. Commented Jul 24, 2015 at 19:24
  • Have you tried implementing your own solution yet? Commented Jul 24, 2015 at 19:27
  • Also you string (or it's contents) can't be json because it's using single quotes instead of double quotes. Commented Jul 24, 2015 at 19:27
  • @deathismyfriend: Processing Json by hand is a waste of time. There are plenty of libraries out there that will do it. Commented Jul 24, 2015 at 19:32

3 Answers 3

3

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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 JObjects is

foreach (JObject jObject in JArray.Parse(json)) {
     // do something with jObject
}

Comments

0
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);

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.