Home > database >  How to get all objects inside an array JSON in a C# controller
How to get all objects inside an array JSON in a C# controller

Time:02-10

How do I retrieve all of the [names] that are part of the object called [items] in this JSON scenario below in C# ?

I am using a shopping cart api and want to show the customer all of the items listed off that were part of the order once they get to the thank you page. The parent object I am looking at in the api is called items and it has child object data such as price of each item, name of each item and product image of each item etc.....

In my controller I was doing this below when I only needed to retrieve simple info like the order only has 1 invoiceNumber, 1 payment method, 1 shipping method, 1 promo code etc.. This code below works and gets me that data in that simple scenario below.

 using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            var obj = JObject.Parse(result);

            
            //Order Info
            string invoiceNumber = (string)obj["invoiceNumber"];
            string email = (string)obj["email"];
            string paymentMethod = (string)obj["paymentMethod"];
            string shippingMethod = (string)obj["shippingMethod"];

            //Discount info
            string amountSaved = (string)obj["discounts"][0]["amountSaved"];
            string promoCode = (string)obj["discounts"][0]["code"];

But now I need to tap into an object called [items] (the data for the items that were part of the order) that is going to have many names of items depending on the number of individual items that were part of the customer order. This is what I attempted but then realized that it would only return one record based on what number I used inside the brackets.

string items = (string)obj["items"][0]["name"]; //This returned the product at index 0
string items = (string)obj["items"][1]["name"]; //This returned the product at index 1
string items = (string)obj["items"][2]["name"]; //This returned the product at index 2

How do I write the syntax so that I can grab ALL of the name objects that currently reside in the item object for exaple? I know it has something to do with deserialize objects and list but I do not know the syntax and how to approach.

Any suggestions on how I can get this done?

CodePudding user response:

the simpliest way

List<string> names = obj["items"].Select(x => (string) x["name"] ).ToList();

test

Console.WriteLine( string.Join(",",names)); // prod1,prod2

more complicated way is to create a c# class and deserialize data. But in this case you will be able to use Linq for queries and search

 List<Item>  items = obj["items"].Select(x => x.ToObject<Item>()).ToList()

public class Item
{
    public string name { get; set; }
    public double price { get; set; }
    public int quantity { get; set; }
}

result (in json format)

[
  {
    "name": "prod1",
    "price": 12.99,
    "quantity": 4
  },
  {
    "name": "prod2",
    "price": 17.65,
    "quantity": 1
  }
]

CodePudding user response:

You can use Newtonsoft json package to convert an object into JSON array. Refer below link

http://www.newtonsoft.com/json/help/html/SerializingJSON.htm

  • Related