Eugene Eugene - 2 months ago 35
C# Question

Get value from List (C# UWP)

I have classes

public class RootObject
{
public int id { get; set; }
public int parent_id { get; set; }
public string status { get; set; }
public string order_key { get; set; }
public string currency { get; set; }
public string version { get; set; }
public bool prices_include_tax { get; set; }
public string date_created { get; set; }
public string date_modified { get; set; }
public int customer_id { get; set; }
public double discount_total { get; set; }
public double discount_tax { get; set; }
public double shipping_total { get; set; }
public double shipping_tax { get; set; }
public double cart_tax { get; set; }
public double total { get; set; }
public double total_tax { get; set; }
public Billing billing { get; set; }
public Shipping shipping { get; set; }
public string payment_method { get; set; }
public string payment_method_title { get; set; }
public string transaction_id { get; set; }
public string customer_ip_address { get; set; }
public string customer_user_agent { get; set; }
public string created_via { get; set; }
public string customer_note { get; set; }
public string date_completed { get; set; }
public string date_paid { get; set; }
public string cart_hash { get; set; }
public List<object> line_items { get; set; }
public List<object> tax_lines { get; set; }
public List<object> shipping_lines { get; set; }
public List<object> fee_lines { get; set; }
public List<object> coupon_lines { get; set; }

}


I get data like this

List<RootObject> rootObjectData = JsonConvert.DeserializeObject<List<RootObject>>(products);
foreach (RootObject root in rootObjectData)
{
int id = root.id;
int customer_id = root.customer_id;

string fio = root.billing.first_name + " " + " " + root.billing.last_name;
string adress = root.billing.address_1 + " " + " " + root.billing.address_2;
double total = root.total;
string telephone = root.billing.phone;


line_items
have
List<object>
type

In
line_items
I have some json with data.

for example

"line_items": [
{
"product_id": 93,
"quantity": 2
},
{
"product_id": 22,
"variation_id": 23,
"quantity": 1
}


],

How I can get for example
product_id
?

Thank's for help so much!

Answer

You can use the very powerful dynamic:

List<dynamic> lineItems = jsonObject.line_items;

foreach (dynamic line_item in lineItems)
{
  int productId = line_item.product_id; 
}

Keep in mind tho:

It can crash because of renaming/other factors - dynamic is very powerful, but to be used this with caution.

Docs: dynamic

You can also access it directly without need for your "class" that you created - simply deserialize to dynamic and access the fields!