0

I'am trying to Read from a Deserilized Json Object. Currently I am using the following code to deserialize the JSON data:

var jsondecode = Newtonsoft.Json.JsonConvert.DeserializeObject(Request.Cookies.Get("wrkb").Value);

Content of my JSON object :

{{
  "shoppingbasket": [
    {
      "price": 12,
      "product": "Lachum",
      "quantity": 2,
      "total": 24
    },
    {
      "price": 2,
      "product": "Laici",
      "quantity": 3,
      "total": 12
    },
    {
      "price": 12,
      "product": "Lachum",
      "quantity": 1,
      "total": 12
    }
  ]
}}

I want to convert this JSON string into a collection of .Net objects that I can work with.

For example, I would like to be able to product this type of output after I have deserialized the object.

Shoppingbasket:
1) Product = Lachum, Price = 12, Quantity = 3, Total = 36
2) Product = Laici, Price = 2, Quantity = 3, Total = 6

Total-Price of basket = 42

This was my solution but, pstrjds's solution elegant :

 DataSet dataSet = Newtonsoft.Json.JsonConvert.DeserializeObject<DataSet>(Request.Cookies.Get("wrkb").Value);
    DataTable dataTable = dataSet.Tables["shoppingbasket"];

    string print = "";
    double basket_total = 0.0;
    foreach (DataRow row in dataTable.Rows)
    {
        print = "Product= " + row["product"] + " Price= " + row["price"] + " Quantity= " + row["quantity"] + " Total= " + row["total"];
        basket_total += Convert.ToInt32(row["total"]);
        <div class="row">
            <ul class="col-md-12">
                <li><div class="col-md-12">@print</div></li>
            </ul>
        </div>
    }

Now I have to fix duplicated Items

cgame92
  • 29
  • 3
  • Could you clarify your question further. What do you mean by "How should I read from this object?" You are showing that you are deserializing it, what exactly are you stuck on? JSON.Net has a generic deserialize option, make a class for your expected data and deserialize an array of those objects. – pstrjds Dec 31 '16 at 12:37
  • I mean how can i work with this object? Is it a array ? – cgame92 Dec 31 '16 at 12:43
  • I have reworded the question slightly and fixed the broken JSON (there were some quotes missing). Please feel free to edit if I have not correctly restated the question. – pstrjds Dec 31 '16 at 13:22

2 Answers2

1

If you don't specify a type for the deserialization, you'll get a jObject. Its properties are deduced on runtime.

dynamic result = JsonConvert.DeserializeObject(json);

Now, there's an another way to get a jObject.

var result = jObject.Parse(json);
var sessionKey = p.GetValue("SessionKey").Value<string>();

Read this. There is no real difference whether to use deserialize or parse if you don't know of the type ahead (as in your case). Either way, you'll get a jObject.

Community
  • 1
  • 1
Lukas
  • 13
  • 6
1

First you need to create a class to work with the returned objects (assuming you know what you are getting ahead of time).

public class ShoppingbasketItem
{
    public double price { get; set; }
    public string product { get; set; }
    public int quantity { get; set; }
    public int total { get; set; }
}
public class Shoppingbasket
{
    public List<ShoppingbasketItem> shoppingbasket { get; set; }
}

Then you can deserialize the objects into your C# code and then do whatever you would need to with them from there.

var products = Newtonsoft.Json.JsonConvert.DeserializeObject<Shoppingbasket>(Request.Cookies.Get("wrkb").Value);

So to compute a sum of the total you could just iterate the list from the basket.

double totalSum = 0.0;
foreach(var item in products.shoppingbasket)
{
    totalSum += item.quantity * item.price;
}

Edit
To achieve the grouping you are looking for, you could do something like this. It is probably not the best solution, but off the top of my head it is what I thought of.

var grouped = new Dictionary<string, ShoppingbasketItem>();

foreach (var item in products.shoppingbasket)
{
    ShoppingbasketItem temp = null;
    if (grouped.TryGetValue(item.product, out temp))
    {
        temp.quantity += item.quantity;
        temp.total += item.total;
    }
    else
    {
        grouped[item.product] = item;
    }
}
pstrjds
  • 16,840
  • 6
  • 52
  • 61
  • Thank you very much. This seems to be the best solution for me! But how can I sum up Items that exist twice or more? – cgame92 Dec 31 '16 at 13:43
  • @cgame92 - I have added an edit showing one way to achieve the grouping. In general on SO you post a new question rather than adding comments or modifying the original question to ask the new question. – pstrjds Dec 31 '16 at 15:24