0

I am new to JSON processing by NewtonSoft on C#. I have the following JSON and trying to get all orderIds and orderNumbers. I tried the following code. But in both cases, I am getting can't access child items error. I also tried using JObject.Parse(json) and tried to get the two values, but got similar errors.

{
  "orders": [{
      "orderId": 123,
      "orderNumber": "234",
      "billTo": {
        "name": "John1 Doe1",
        "Street": "1 one way"
      },
      "items": [{
        "orderItemId": 46429,
        "lineItemKey": "110",
        "sku": "Hammer",
        "name": "Small Hammer"
      }]
    },
    {
      "orderId": 567,
      "orderNumber": "789",
      "billTo": {
        "name": "John2 Doe2",
        "Street": "2 second way"
      },
      "items": [{
        "orderItemId": 76567,
        "lineItemKey": "213",
        "sku": "Tape",
        "name": "Electric Tape"
      }]
    },
    {
      "orderId": 223,
      "orderNumber": "334",
      "billTo": {
        "name": "John3 Doe4",
        "Street": "3 third way"
      },
      "items": [{
        "orderItemId": 87890,
        "lineItemKey": "890",
        "sku": "Box",
        "name": "Wooden box"
      }]
    }
  ]
}
  dynamic dynJson = JsonConvert.DeserializeObject(json);
foreach (var item in dynJson)
{
    //Console.WriteLine("{0} {1} \n", item["orders"].orderId, 
                        item["orders"].orderNumber);
    Console.WriteLine("{0} {1} \n", item["orders"]["orderId"], item["orders"] 
                       ["orderNumber"]);
}
6
  • Removed the backslashes.
    – Kim
    Jun 23, 2021 at 19:36
  • 4
    Have you considered defining a type to represent this information, telling Newtonsoft to deserialize your JSON to that type, then using Linq to operate on that data to extract the information you want?
    – mason
    Jun 23, 2021 at 19:38
  • 2
    why NewtonSoft when you can use System.Text.Json?
    – Iria
    Jun 23, 2021 at 19:48
  • 1
    @Iria: Because we've been using Newtonsoft for years - we are comfortable with it.
    – Flydog57
    Jun 23, 2021 at 20:13
  • well, aparently, not comfortable enough as you don't know how to use it
    – Iria
    Jun 24, 2021 at 13:26

4 Answers 4

1

I made it to works as follows:

        var jObj = JObject.Parse(json);

        JArray orders = (JArray)jObj["orders"];
        foreach (JToken order in orders)
        {
            string orderId = (string)order["orderId"];
            string orderNumber = (string)order["orderNumber"];
        }
0

The for loop statement seems to be wrong since dynJson is an object and not an array. You need to loop through the dynJson.orders, like below.

dynamic dynJson = JsonConvert.DeserializeObject(data);
    foreach (var item in dynJson.orders)
    {
        //Console.WriteLine("{0} {1} \n", item["orders"].orderId, 
                            //item["orders"].orderNumber);
        Console.WriteLine("{0} {1} \n", item.orderId,
                           item.orderNumber);
    }
}

Above code will print out

123 234 
567 789 
223 334
1
  • This didn't work. I got "orderId" not defined error.
    – Kim
    Jun 23, 2021 at 20:21
0

You may want to do this in a strongly typed fashion. In that case, you need to create a few classes that can be used to hold your information.

Starting at the deepest end of the hierarchy, first the item:

public class Item
{
    public int orderItemId { get; set; }
    public string lineItemKey { get; set; }
    public string sku { get; set; }
    public string name { get; set; }
}

Then the Bill To information:

public class BillTo
{
    public string name { get; set; }
    public string Street { get; set; }
}

Then an order, which has a BillTo and a bunch of Items:

public class Order
{
    public int orderId { get; set; }
    public string orderNumber { get; set; }
    public BillTo billTo { get; set; }
    public List<Item> items { get; set; }
}

and then, because your JSON starts with an object containing a bunch of orders:

public class Orders
{
    public List<Order> orders { get; set; }
}

If you run this:

var result = JsonConvert.DeserializeObject<Orders>(theJson);
foreach (var order in result.orders)
{
    Debug.WriteLine($"Order #{order.orderId}: For {order.billTo.name}, {order.items.Count} items");
}

You end up with:

Order #123: For John1 Doe1, 1 items
Order #567: For John2 Doe2, 1 items
Order #223: For John3 Doe4, 1 items
-4

While Vinit's answer will no doubt work, we generally try to avoid using dynamic in C#. When we use dynamic, it erases some of the advantages of strongly typed coding, which is one of the great things about C#.

So instead, we can define types to represent our data:

class PostedOrders
{
    public List<Order> Orders { get; set; }
}

class Order
{
    public int OrderId { get; set; }

    public string OrderNumber { get; set; }

    public BillRecipient BillTo { get; set; }

    public List<Item> Items { get; set; }
}

class BillRecipient
{
    public string Name { get; set; }
  
    public string Street { get; set; } 
}

class Item
{
    public int OrderItemId { get; set; }

    public string LineItemKey { get; set; }

    public string Sku { get; set; }

    public string Name { get; set; }
}

Now that we have defined everything, we get the full benefits of Intellisense, code completion, type checking, and easy refactoring.

To work with the JSON, we can simply iterate through the array. And to write it out to the console, we can use string interpolation which has a nicer syntax than the old format strings.

PostedOrders orders = JsonConvert.DeserializeObject<PostedOrders>(json);

foreach (var order in orders.Orders)
{
    Console.WriteLine($"{order.OrderId} {order.OrderNumber}");
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.