Json Navigation

Muhammad Ahmed 1 Reputation point
2020-12-06T07:14:13.157+00:00

I am getting a string from a Rest API. The string contains a list of orders.

string result = await content.ReadAsStringAsync();
dynamic json = JsonConvert.DeserializeObject(result);
string res = json[0]["id"];
MessageBox.Show( res.ToString());

I can see the individual order IDs but I need to get all order IDs. Then I have to process each order ID separately. I may need a loop or some other mechanism. Can anybody help?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,223 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,031 Reputation points
    2020-12-06T12:12:54.35+00:00

    Hello @Muhammad Ahmed

    The best path is to deserialize to a list which allows you to have better control such as using a for/next or the ability to use linq to find information. Below shows using a class to read the data while the other uses a slight variation of what you presented. If these do not work for you let me know why/

    Example using Newtonsoft.Json

    Json (with minimal information)

    [  
        {  
            "id": 1,  
            "customerId": 100  
        },  
        {  
            "id": 2,  
            "customerId": 234  
        },  
        {  
            "id": 3,  
            "customerId": 300  
        },  
        {  
            "id": 4,  
            "customerId": 234  
        }  
    ]  
    

    Class to contain above data.

    public class Order  
    {  
        public int id { get; set; }  
        public int customerId { get; set; }  
    }  
    

    Deserialize

    using System;  
    using System.Collections.Generic;  
    using System.IO;  
    using System.Linq;  
    using System.Text;  
    using System.Threading.Tasks;  
    using JsonSampleLibrary.Classes;  
    using Newtonsoft.Json;  
      
    namespace JsonSampleLibrary  
    {  
        public class DynamicOperations  
        {  
            public static List<Order> ReadOrdersStrongTyped(string fileName)  
            {  
                return JsonConvert.DeserializeObject<List<Order>>(File.ReadAllText(fileName));  
            }  
        }  
    }  
    

    Work with the deserialized data first traversing all then using lambda to get orders for a specific customer.

    var ordersList = DynamicOperations.ReadOrdersStrongTyped("orders.json");  
      
    for (int index = 0; index < ordersList.Count; index++)  
    {  
        Console.WriteLine(ordersList[index].id);  
    }  
      
    Console.WriteLine();  
      
    var id = 234;  
      
    var specificOrder = ordersList.Where(order => order.customerId == id).ToList();  
      
    for (int index = 0; index < specificOrder.Count(); index++)  
    {  
        Console.WriteLine(specificOrder[index].id);  
    }  
    

    Then the other way is with no class similar to what you have.

    using System;  
    using System.Collections.Generic;  
    using System.IO;  
    using System.Linq;  
    using System.Text;  
    using System.Threading.Tasks;  
    using JsonSampleLibrary.Classes;  
    using Newtonsoft.Json;  
      
    namespace JsonSampleLibrary  
    {  
        public class DynamicOperations  
        {  
            public static void ReadOrders1(string fileName)  
            {  
                var jsonString = File.ReadAllText(fileName);  
                var objects = JsonConvert.DeserializeObject<dynamic>(jsonString);  
                foreach (var o in objects)  
                {  
                    Console.WriteLine($"{o.id}");  
                }  
            }  
      
        }  
    }  
    

    In the above o.id is known as an integer e.g. testing the type

    foreach (var o in objects)  
    {  
        JValue id = o.id;  
        Console.WriteLine($"{id.Type}");  
    }  
    

    And typing id column

    public static void ReadOrders1A(string fileName)  
    {  
        var jsonString = File.ReadAllText(fileName);  
        var objects = JsonConvert.DeserializeObject<dynamic>(jsonString);  
        List<int> identifiers = new List<int>();  
        foreach (var o in objects)  
        {  
            identifiers.Add(Convert.ToInt32(o.id));  
        }  
    }  
    
    
    
    
    
    
      
    
    0 comments No comments