8

Feels like there is a one-two row solution for what I want to do: Parse a string like this:

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

Into something like this:

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

Whats the simplest way to do this?

5 Answers 5

23
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();
3
  • Hi .. this method throws an exception when i try to deserialize a json string containing multiple objects. Is there a way to resolve that ? Commented May 15, 2014 at 8:42
  • please ignore my comment above, the JavaScriptSerializer().DeserializeObject() method seems to be working fine . Commented May 15, 2014 at 8:46
  • Awesome. :) quick and neat :) '+1' from me. Commented Mar 10, 2017 at 11:52
8

You could 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 post : JSON to string array in C#
Lib : http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx

4

It looks like your input string is a JSON string, for which you can use a JSON deserializer if you want. If not you can use regular-expression along with named-groups as the following:

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 regular-expression are indicated by (?<group-name>pattern). In the above pattern we have two named groups: key, and value which can be grabbed from the Match object using the Groups indexer.

3

You could use JavaScriptSerializer to serialize the json into a dynamic object which would allow you to access the properties via name e.g.

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

I just ran into a similar rabbit hole. This helped me with out any other .dll installs. Hope this helps someone.

using System.Text.Json.Nodes;

public static string cSettings = AppDomain.CurrentDomain.BaseDirectory + @"\Application_Settings.json";

public static void Read_JSON() 
{
   string read = File.ReadAllText(cSettings);

   var jsonObject = JsonNode.Parse(read);

   var appname = jsonObject["appname"];

   MessageBox.Show(appname.ToString());
}

//output: my test app

Application_Settings.json


{
  "appname": "my test app",
  "version": "1.0.003",
  "id": null,
  "firstrun": null,
  "firstname": "t",
  "lastname": "t",
  "email": "[email protected]",
  "cpu1id": "F00A20F10",
  "cpu1key": null,
  "gamingpc": false
}

Link to where I found this reference.

I'm using Visual Studio 2022 C#

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.