1

I have the following Json collection and I need to represent it as a .Net collection. Esentially it is a key-value pair list with the keys (col) possibly having dublicates (dictionary is out at this stage).

I sorting and grouping would be nice but not essential. Can any help identify what the best .Net enumeration would be the best fit please?

[
    {
        "col": "thiscol",
        "val": "thisval"
    },
    {
        "col": "thiscol",
        "val": "thisval2"
    },
    {
        "col": "thiscol2",
        "val": "thisval2"
    },
    {
        "col": "thiscol3",
        "val": "thisval3"
    }
]

5 Answers 5

13

using Json.Net

dynamic dynObj = JsonConvert.DeserializeObject(yourstring);
foreach (var item in dynObj)
{
    Console.WriteLine(item.col + " " + item.val);
}

or

JArray jArray = (JArray)JsonConvert.DeserializeObject(yourstring);
var newlist = jArray.OrderByDescending(x => x["val"]).ToArray();

or

JArray jArray = (JArray)JsonConvert.DeserializeObject(yourstring);
dynamic dynObj1 = jArray.OrderByDescending(x => x["val"]);
foreach (var item in dynObj1)
{
    Console.WriteLine(item.col + " " + item.val);
}

or with built-in JavaScriptSerializer & dynamic

dynamic dynObj2 = new JavaScriptSerializer().Deserialize<List<object>>(yourstring);
foreach (var item in dynObj2)
{
    Console.WriteLine(item["col"] + " " + item["val"]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use a lookup in this case, basically a dictionary that allows multiple values for each key - with Linq you can project to a lookup using ToLookup(). Note that lookups are immutable though - that might not fit your bill.

Alternatively of course you can just use a Dictionary<T,IList<U>> (or IEnumerable<U>) using a collection as your value type - dictionaries are flexible like that.

Comments

1

IEnumerable<YourObject> where YourObject is a class you define to hold these values. I recommend using Json.Net to parse the json. Then you can just use linq to manage the IEnumerable you get back.

Comments

1

Have you looked at NameValueCollection?

Comments

0

JArray arr = JArray.Parse(Your string);

After that using for loop to get the values,

Comments

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.