Reputation: 231
I have JSON like this
"id": 823,
"parent_id": 0,
"status": "on-hold",
"order_key": "wc_order_562b39a2050f2",
"currency": "USD",
"version": "2.4.7",
"prices_include_tax": false,
"date_created": "2015-10-24T07:56:18",
"date_modified": "2015-10-24T07:56:18",
"customer_id": 0,
"discount_total": 0.00,
"discount_tax": 0.00,
"shipping_total": 0.00,
"shipping_tax": 0.00,
"cart_tax": 0.00,
"total": 76.98,
"total_tax": 0.00,
I parse it like this `
RestAPI rest = new RestAPI("*******", "*******", "*********");
WCObject wc = new WCObject(rest);
//Get all products
var orders = await wc.GetOrders(new Dictionary<string, string>() {
{ "per_page", "100" }});
string products = orders.ToFormattedJsonString();`
I need to take for example "total"
field and write it to field in database.
For database write I have for example this code MySqlCommand addCommand = new MySqlCommand("INSERT INTO demotable (salary,surname) VALUES (1234,'Luk')", connection);
addCommand.ExecuteNonQuery();
But I can have much orders. I need to do this for each order in JSON.
How I can do this?
Upvotes: 1
Views: 1148
Reputation: 38905
Your JSON is an array, so if you just want one piece of information from each item, you can get it into a JArray
to grab the info you want. This is simpler than deserializing to a class you do not need and are not going to use:
string jstr = ... from whereever ...
// get into array
var jobj = JArray.Parse(jstr);
for (int n = 0; n < jobj.Count - 1; n++)
{
// save to a List or update DB
Console.WriteLine(jobj[n]["email"]);
}
Partial result:
If you need lots of the pieces, you may want to deserialize it to an array or list of T and loop thru that.
Upvotes: 2
Reputation: 3923
@Plutonix Answer is correct. But I want to show another way of handling this.
Newtonsoft Json is a popular Json Parser that can be achieved this. This is a very useful package. install this package from the link.
so if your json string is
string products = orders.ToFormattedJsonString();
your code will be
List<RootObject> rootObjectData = JsonConvert.DeserializeObject<List<RootObject>>(products);
now you can loop through items like below.
foreach(RootObject root in rootObjectData)
{
foreach(Class1 c in root.Property1)
{
int id = c.id;
}
}
Note: I used RootObject
here from the pastebin URL that you mentioned in your comments.
Upvotes: 1
Reputation: 3887
Deserialize your JSON to an IEnumerable using Json.net
. use a loop to iterate through your deserialized collection and execute a query for each of them.
Upvotes: 0