Eugene Eugene - 2 months ago 7
C# Question

Write JSON value to SQL database

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?

Answer

@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)
{
    //You will get all your class elements from which you can get data..
}

Note: I used RootObject here from the pastebin URL that you mentioned in your comments.