How to split key/value pairs in an array?

I have this type of key value is stored in my database:

[{"SelFoodId":"2","SelQuantity":"5"},
 {"SelFoodId":"7","SelQuantity":"3"},
 {"SelFoodId":"9","SelQuantity":"7"}]

But now I want to split this JSON array in this form in c# like

SelFoodId = {2,7}, SelQuantity  = {5,7}

1 answer

  • answered 2018-05-16 05:54 TheGeneral

    1. Go here (json2csharp) and create some objects out of your JSON

    Which will give you something like this

    public class MyAwesomeSomething
    {
        public string SelFoodId { get; set; }
        public string SelQuantity { get; set; }
    }
    

    2. Add the Json.NET Nuget package Newtonsoft.Json

    3. Look up JsonConvert.DeserializeObject Method (String) and this helpful sample

    Deserializes the JSON to a .NET object.n.

    4. Write some code

    Exmaple

    var json = "[{\"SelFoodId\":\"2\",\"SelQuantity\":\"5\"},{\"SelFoodId\":\"7\",\"SelQuantity\":\"3\"},{\"SelFoodId\":\"9\",\"SelQuantity\":\"7\"}]";
    var list = JsonConvert.DeserializeObject<List<MyAwesomeSomething>>(json);    
    foreach(var item in list)       
    {   
        Console.WriteLine(item.SelFoodId + " " + item.SelQuantity);
    }
    

    Output

    2 5
    7 3
    9 7
    

    Full Demo Here