Parse JSON String to list <string>

 string json = "{\"People\":[{\"FirstName\":\"Hans\",\"LastName\":\"Olo\"} {\"FirstName\":\"Jimmy\",\"LastName\":\"Crackedcorn\"}]}"; var obj = JObject.Parse(json); List<string> first; List<string> last; foreach (var child in obj["People"].Children()) { var name = child.First()["countryName"].ToString(); var two = child.First()["countryCode"].ToString(); var three = child.First()["isoAlpha3"].ToString(); countries.Add(name); twoCharCodes.Add(two); threeCharCodes.Add(three); Console.Write("Name:\t\t{0}\n2CharCode:\t{1}\n3CharCode:\t{2}\n\n", name, two, three); } 

I am looking for a way to add each FirstName value to the first list and the same with LastName validation and last list. What is the best way to do this?

The above code is broken into:

 var name = child.First()["countryName"].ToString(); 

with this error:

  Cannot access child value on Newtonsoft.Json.Linq.JProperty 

Any tips?

+5
source share
4 answers

This seems like a bad way (creating two correlated lists), but I assume you have reasons.

I would parse the JSON string (which has a typo in your example, it skips the comma between two objects) into a strongly typed object, and then uses a pair of LINQ queries to get two lists.

 void Main() { string json = "{\"People\":[{\"FirstName\":\"Hans\",\"LastName\":\"Olo\"},{\"FirstName\":\"Jimmy\",\"LastName\":\"Crackedcorn\"}]}"; var result = JsonConvert.DeserializeObject<RootObject>(json); var firstNames = result.People.Select (p => p.FirstName).ToList(); var lastNames = result.People.Select (p => p.LastName).ToList(); } public class Person { public string FirstName { get; set; } public string LastName { get; set; } } public class RootObject { public List<Person> People { get; set; } } 
+9
source

Since you are using JSON.NET, I personally would go with serialization so that you can support Intellisense for your object. You will need a class that represents your JSON structure. You can create this manually, or you can use something like json2csharp to generate it for you:

eg.

 public class Person { public string FirstName { get; set; } public string LastName { get; set; } } public class RootObject { public List<Person> People { get; set; } } 

Then you can simply call the JsonConvert methods to deserialize the JSON into an object:

 RootObject instance = JsonConvert.Deserialize<RootObject>(json); 

Then you have Intellisense:

 var firstName = instance.People[0].FirstName; var lastName = instance.People[0].LastName; 
+6
source

I use this JSON Helper class in my projects. I found it on the net a year ago, but lost the original URL. So I paste it directly from my project:

 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Runtime.Serialization.Json; using System.IO; using System.Text; /// <summary> /// JSON Serialization and Deserialization Assistant Class /// </summary> public class JsonHelper { /// <summary> /// JSON Serialization /// </summary> public static string JsonSerializer<T> (T t) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, t); string jsonString = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return jsonString; } /// <summary> /// JSON Deserialization /// </summary> public static T JsonDeserialize<T> (string jsonString) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); T obj = (T)ser.ReadObject(ms); return obj; } } 

You can use it as follows: Create classes as Craig V. suggested.

And then deserialize like that

 RootObject root = JSONHelper.JsonDeserialize<RootObject>(json); 
0
source

It is required to post this as a comment as a note on the accepted answer, but this is a bit unclear. As clean as a note:

If you do not need the objects themselves, and you want your project to be cleared of other unused classes, you can parse something like:

 var list = JObject.Parse(json)["People"].Select(el => new { FirstName = (string)el["FirstName"], LastName = (string)el["LastName"] }).ToList(); var firstNames = list.Select(p => p.FirstName).ToList(); var lastNames = list.Select(p => p.LastName).ToList(); 

Even when using a strongly typed person class, you can skip the root object by creating a list using JObject.Parse(json)["People"].ToObject<List<Person>>() Of course, if you need to reuse objects, it's better to create them from the very beginning. Just wanted to point to an alternative;)

0
source

All Articles