0

I am using VS2010 with C# 4. I have JSON similar to the following:

{"ItemDetails":{"Item":{"val": [ 
{"Description":"Desk1","Amount":"100.00"},
{"Description":"Desk2","Amount":"200.00"},
{"Description":"Desk3","Amount":"300.00"}]}}}

I want to get all the amount values into one string array like what is shown below:

amount={100.00,200.00,300.00}

How could I implement this? Do I have to loop through the JSON object or is there another way to do this?

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
niknowj
  • 977
  • 4
  • 19
  • 37
  • What platform are you working on? Windows 8 has API's, on other platforms you would probably use JSON.Net from Newtonsoft. -> I take it from your addition of "VS2010" to the question that you're not developing for Windows 8. Use the JSON.NET Nuget package then. – Kris Vandermotten Jun 10 '14 at 09:47
  • 1
    Search this site before posting common questions like this, there are plenty of result on it like http://stackoverflow.com/questions/17617594/how-to-get-some-values-from-a-json-string-in-c which itself contains loads of help from many people – Mo Patel Jun 10 '14 at 09:49
  • "do I have to loop through the Josn object" -> You could use a Linq query. But is this a question about Linq or about JSON parsing? Please be more precise. – Kris Vandermotten Jun 10 '14 at 09:54

3 Answers3

0

I would recommend using NewtonSofts JSON library, but another (yet ugly) way is to use Regular Expressions.

var json = "{\"ItemDetails\":{\"Item\":{\"val\": [ " +
                       "{\"Description\":\"Desk1\",\"Amount\":\"100.00\",}," +
                       "{\"Description\":\"Desk2\",\"Amount\":\"200.00\",}," +
                       "{\"Description\":\"Desk3\",\"Amount\":\"300.00\"}}}";


// What I think you want
var amount = Regex.Matches(json, "Amount\":\"(.*?)\"").Cast<Match>().Select(m => m.Groups[1].Value).ToArray();

// Values 'converted' to json
var jsonAmount = "amount={" + string.Join(",", amount) + "}";
Sasse
  • 1,108
  • 10
  • 14
  • What if there is whitespace in the JSON? – Brian Rogers Jun 12 '14 at 02:23
  • Then it won't work just like it is. You would need to add support for that in the pattern. Add "\s" to ignore whitespaces in some places. Like: Amount\"\s:\s\"(.*?)\". But like I said, I would recommend using NewtonSofts JSON library or another JSON library. Otherwise you have .NET's JavaScriptSerializer but that's not a very good one. Not yet at least: http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx – Sasse Jun 12 '14 at 06:13
  • Agreed, using Regex to parse JSON is not such a great idea. Much better to use a proper parser. – Brian Rogers Jun 12 '14 at 07:25
0

Using Json.Net you can do this with a LINQ-to-JSON query:

string json = @"
{
    ""ItemDetails"": {
        ""Item"": {
            ""val"": [
                {
                    ""Description"": ""Desk1"",
                    ""Amount"": ""100.00""
                },
                {
                    ""Description"": ""Desk2"",
                    ""Amount"": ""200.00""
                },
                {
                    ""Description"": ""Desk3"",
                    ""Amount"": ""300.00""
                }
            ]
        }
    }
}";

JToken token = JToken.Parse(json);
string[] amounts = token.SelectToken("ItemDetails.Item.val")
                        .Children()
                        .Select(t => t["Amount"].ToString())
                        .ToArray();

Console.WriteLine("amount={" + string.Join(",", amounts) + "}");

Output:

amount={100.00,200.00,300.00}
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
-1

I am assuming you are not using JSON.NET. If this the case, then you can try it.

It has the following features -

LINQ to JSON The JsonSerializer for quickly converting your .NET objects to JSON and back again Json.NET can optionally produce well formatted, indented JSON for debugging or display Attributes like JsonIgnore and JsonProperty can be added to a class to customize how a class is serialized Ability to convert JSON to and from XML Supports multiple platforms: .NET, Silverlight and the Compact Framework Look at the example below.

In this example, JsonConvert object is used to convert an object to and from JSON. It has two static methods for this purpose. They are SerializeObject(Object obj) and DeserializeObject(String json) -

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string json = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "Expiry": "2008-12-28T00:00:00",
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject(json);

MRebai
  • 5,344
  • 3
  • 33
  • 52