I am new to JSON.NET and not sure how to do this.
I have the CartItem
class, and I need to implement
GetAllCartItemsFromArbitraryJson(string jsonStr)
, as follows:
class CartItem {
public int Id;
public int Qty;
}
List<CartItem> items = GetAllCartItemsFromArbitraryJson(jsonStr);
All I know is jsonStr
contains one or more cartitems
somewhere (I don't know how deep), eg.
{
... : {
"cartitems": [{
"id": "1",
"qty": "1"
},{
"id": "2",
"qty": "5"
}
]
},
... : {
... : {
...,
"cartitems": [{
"id": "10",
"qty": "2"
}
]
}
}
}
This function needs to collect all the cartitems
and put it in List<CartItem>
List<CartItem> GetAllCartItemsFromArbitraryJson(string jsonStr) {
JObject json = JObject.Parse(jsonStr);
// then what...?
}
So the List<CartItem>
will contains:
Id Qty
1 1
2 5
10 2
How would you do it in C#?