Search code examples
c#jsonstring-parsing

How to extract numbers from string array/dictionary using c#?


I have a string where its a string of a array of dictionaries.

An example of the format is:

[{"id":1,"items":[5,8]},{"id":2,"items":[6]},{"id":3,"items":[7]}]

(Note: all the above code is a string)

So here it is a string of an array of dictionaries that has two keys, the value of the first key is a number, and the value of the second key is a array of numbers.

Using c# (out of the box assemblies), how can I iterate through all the id values, and then all the item array values.

So I would expect like a double for loop. One to iterate through the id's and extract the number, and then for each iteration it would need to iterate through all the values of the items array.

Does anyone know how to go about parsing and extracting the numbers?

Thanks.

The output would be like ( for example )

1
 5  8
2
 6
3
 7

EDIT:

I tried this:

            string dataString = JSONValue.Text;
            JavaScriptSerializer jss = new JavaScriptSerializer();
            var json = new JavaScriptSerializer();
            var data = json.Deserialize<List<Dictionary<string, Object>>>(dataString);

            int sectionID;
            List<int> itemIDS;
            foreach (Dictionary<string, Object> dict in data)
            {
                sectionID = (int)dict["id"];
                itemIDS = (List<int>)dict["items"];
                ReportObject.log(sectionID.ToString());
                foreach (int itemID in itemIDS)
                {
                    ReportObject.log(itemID.ToString());
                }
            }

But am getting

(6/27/2013 12:02:04 AM) - Error Message: Unable to cast object of type 'System.Collections.ArrayList' to type 'System.Collections.Generic.List`1[System.Int32]'.

Solution

  • try this

    using using System.Web.Script.Serialization;
    var jsonStr = "[{\"id\":1,\"items\":[5,8]},{\"id\":2,\"items\":[6]},{\"id\":3,\"items\":[7]}]";
    var json = new JavaScriptSerializer();
    var data = json.Deserialize<List<dynamic>>(jsonStr);
    

    this will generate a list of dynamic object with two properties id and items, then you can loop through that list and retrieve the info which you want.

    The dynamic keyword only available from .net 4.0 or later. Otherwise you can use the following option.

    create a class like this

    public class Info{
          public int Id { get; set; }
          public int[] Items { get; set; }
    }
    

    and then var data = json.Deserialize<List<Info>>(jsonStr);