Split this json string into array C # string

There seems to be a one-line solution for what I want to do: Parse the line as follows:

"{\"postalcode\":\"12345\",\"postalcity\":\"SOME-CITY\",\"country\":\"UK\",\"box\":false}" 

In something like this:

  string[] result = { "12345", "SOME-CITY", "UK", "false" }; 

What is the easiest way to do this?

+6
source share
4 answers
 string json = "{\"postalcode\":\"12345\",\"postalcity\":\"SOME-CITY\",\"country\":\"UK\",\"box\":false}"; var dict = new JavaScriptSerializer().Deserialize<Dictionary<string,object>>(json); var postalCode = dict["postalcode"]; //Array is also possible string[] result = dict.Select(kv => kv.Value.ToString()).ToArray(); 
+18
source

You can also use newtonsoft: http://james.newtonking.com/pages/json-net.aspx

 string json = @"{ ""Name"": ""Apple"", ""Expiry"": new Date(1230422400000), ""Price"": 3.99, ""Sizes"": [ ""Small"", ""Medium"", ""Large"" ] }"; JObject o = JObject.Parse(json); string name = (string)o["Name"]; // Apple JArray sizes = (JArray)o["Sizes"]; string smallest = (string)sizes[0]; // Small 

I found another related entry: JSON for a string array in C #

Lib: http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx

+5
source

You can use JavaScriptSerializer to serialize json into a dynamic object that will allow you to access properties through a name, e.g.

 var address = new JavaScriptSerializer().Deserialize<dynamic>(json); Console.WriteLine(address["postalcode"]); 
+2
source

It looks like your input line is a JSON line for which you can use the JSON deserializer if you want. If not, you can use the regex with named groups as follows:

 List<string> values = new List<string>(); List<string> keys= new List<string>(); string pattern = @"\""(?<key>[^\""]+)\""\:\""?(?<value>[^\"",}]+)\""?\,?"; foreach(Match m in Regex.Matches(input, pattern)) { if (m.Success) { values.Add(m.Groups["value"].Value); keys.Add(m.Groups["key"].Value); } } var result = values.ToArray(); 

Named groups in the regular expression are indicated by the symbol (?<group-name>pattern) . In the above template, we have two named groups: key and value , which can be captured from the Match object using the Groups indexer.

+2
source

All Articles