Fetch data for a specific field in Web API C#

Abdeali Mandviwala 20 Reputation points
2024-01-03T23:40:13.5766667+00:00

Hello,

I have a Json URI which I am using as a data source. I am writing a web api wherein I need to retrieve the data for any of the specific field which user inputs. For e.g, below json is my data source and I need to fetch data only for table_no. So the user will input the field as table_no and the response should only show data with table_no only.

    data": [
    {

            "order": 1,

            "table_no": 94683,

            "table_book_date": "20240103100000",

        },

		{

            "order": 2,

            "table_no": 94544,

            "table_book_date": "20240103100000",

        }

	]
        ```

I have this below C# code but not sure how to use "element" (which is an input for any field (here it is table_no)) to filter my json data source.

```csharp
[HttpGet("[action]/{element}")]
public async Task<IActionResult> Get(string element)
{
    try
    {
      
        var resturantData = await DeSerializeJsonData(element);

        return Ok(new
        {
            resturantData.data
        });
    }
    catch (HttpRequestException httpRequestException)
    {
        return BadRequest($"Error getting info");
    }
}
 private async Task<ResturantData> DeSerializeJsonData(string element)
 {
     using (var client = new HttpClient())
     {
         var response = await client.GetFromJsonAsync<ResturantData>($"<json url>.json");
         return response;
     }
 }
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,346 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
314 questions
0 comments No comments
{count} votes

Accepted answer
  1. Ping Ni-MSFT 3,195 Reputation points Microsoft Vendor
    2024-01-04T08:14:58.8233333+00:00

    Hi @Abdeali Mandviwala,

    You can use JSON.NET to achieve your requirement. Be sure install Microsoft.AspNetCore.Mvc.NewtonsoftJson package If your project version is beyond .NET Core 3.x.

    A simple working demo you could follow:

    string jsonString = @"{
    ""data"": [
        {
            ""order"": 1,
            ""table_no"": 94683,
            ""table_book_date"": ""20240103100000""
        },
        {
            ""order"": 2,
            ""table_no"": 94544,
            ""table_book_date"": ""20240103100000""
        }
    ]
    }";
    
    var jsonObject = JsonConvert.DeserializeObject<JObject>(jsonString);
    
    var dataArray = jsonObject["data"] as JArray;
    
    var resultData = new List<object>();
    var element = "table_no";
    foreach (var item in dataArray)
    {
        var tableNo = item[element];
        resultData.Add(new { table_no = tableNo });
    }
    
    var resultObject = new { data = resultData };
    string resultJson = JsonConvert.SerializeObject(resultObject, Formatting.Indented);
    
    // Print the result
    Console.WriteLine(resultJson);
    

    Result:

    User's image


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Rena

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. SurferOnWww 2,406 Reputation points
    2024-01-04T01:25:58.1066667+00:00

    (1) The JSON string shown in your post is not correct. Make correction as follows:

    {
      "data": [
        {
          "order": 1,
          "table_no": 94683,
          "table_book_date": "20240103100000"
        },
        {
          "order": 2,
          "table_no": 94544,
          "table_book_date": "20240103100000"
        }
      ]
    }
    

    (2) Generate the class definition form the JSON string using the "Paste Special" function of the Visual Studio, as shown below:

    enter image description here

    As for the result, see Rootobject and Datum classes in the sample code shown in step (3) below.

    (3) Deserialize the JSON string using the libraries of Newtonsoft.Json or System.Text.Json as shown in the following sample code:

    using Newtonsoft.Json;
    using System;
    
    namespace ConsoleAppJson
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                var path = @"C:\Users\...\Sample.json";  // path to json file
                String jsonString;
                using (var sr = System.IO.File.OpenText(path))
                {
                    jsonString = sr.ReadToEnd();
                }
    
                // Newtonsoft.Json
                var result1 = JsonConvert.DeserializeObject<Rootobject>(jsonString);
                foreach(Datum order in result1.data)
                {
                    Console.WriteLine(order.table_no);
                }
    
                Console.WriteLine("----------------");
    
                // System.Text.Json
                var result2 = System.Text.Json.JsonSerializer.Deserialize<Rootobject>(jsonString);
                foreach (Datum order in result2.data)
                {
                    Console.WriteLine(order.table_no);
                }
    
    
                Console.Read();
            }
        }
       
        public class Rootobject
        {
            public Datum[] data { get; set; }
        }
    
        public class Datum
        {
            public int order { get; set; }
            public int table_no { get; set; }
            public string table_book_date { get; set; }
        }
    }
    

    (4) Output is shown below:

    enter image description here