Leveraging LINQ to JSON for extracting distinct elements from a collection

Having trouble organizing a list of objects/values from a JSON feed using LINQ? Here is what my JSON feed looks like:

{
   "Project":[
      {
         "ID":"XY1212",
         "Name":"Some Name",
         "Description":"U.S. No 2 Diesel Retail Prices",
         "Manager":"Nora Sims",
         "Dept":"HR",
         "Updated":"2014-07-22",
         "Statistics":[
            [
               "20140722",
               32.22
            ],
            [
               "20140721",
               55
            ],
            ...
         ]
      }
   ]
}

To structure this data, I have created the following classes:

public class Project
{
    public string ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Manager { get; set; }
    public string Dept { get; set; }
    public string Updated { get; set; }
    public List<List<object>> Statistics { get; set; }
}

public class RootObject
{
    public List<Project> Project { get; set; }
}

public class Statistic
{
    public Datetime ProjectDate { get; set; }
    public Decimal Sale { get; set; }
}

Now onto parsing the feed and extracting only the "Statistics" data:

HttpClient() http = new HttpClient();
var json = await http.GetStringAsync(uri);

JObject jo = JObject.Parse(json);
var jList = from values in jo["Project"].Children()["Statistics"]
    select values;

By looping through jList, I am able to access all the values, but it seems to loop only once. I want to iterate through each array within the [0] I see during debugging.

If you have any advice on how to achieve this, please let me know. Thank you!

Answer №1

If you're facing difficulties with handling unconventional JSON for your Project class, creating a custom JsonConverter specifically for your Statistic class can be the solution. This converter will allow you to define the structure of your Project class in the desired manner.

Below is the code snippet for the converter:

class StatisticConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(Statistic));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JArray array = JArray.Load(reader);
        return new Statistic
        {
            ProjectDate = DateTime.ParseExact(array[0].ToString(), "yyyyMMdd",
                            System.Globalization.CultureInfo.InvariantCulture),
            Sale = array[1].ToObject<decimal>()
        };
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

To integrate the converter, make some adjustments to your classes. Firstly, update the type of the Statistics property within the Project class to List<Statistic> instead of List<List<object>>. Even though it differs from the JSON format, the converter will handle this discrepancy.

public class Project
{
    public string ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Manager { get; set; }
    public string Dept { get; set; }
    public string Updated { get; set; }
    public List<Statistic> Statistics { get; set; }
}

Then, add a [JsonConverter] attribute to the Statistic class to link it with the customized converter:

[JsonConverter(typeof(StatisticConverter))]
public class Statistic
{
    public DateTime ProjectDate { get; set; }
    public Decimal Sale { get; set; }
}

With these adjustments, deserialization will yield the list of statistics formatted according to your preferences.

RootObject root = JsonConvert.DeserializeObject<RootObject>(json);

Experience a live demonstration here.

Answer №2

The issue lies not in your code but rather in the structure of the JSON string being returned by the HttpClient. The JSON string contains parts without keys, making it difficult to navigate. Additionally, each element of the statistic is nested within another child.

However, with the following code snippet, I am able to extract the values of Statistics individually:

JObject jo = JObject.Parse(json);
            var jList = from values in jo["Project"]
                        select values;
            foreach (var j in jList)
            {
                var l = j["Statistics"].Children();
                foreach (var m in l.Children())
                {
                    string a = m.ToString();
                }
            }

During the first loop, variable 'm' contains the Date, and during the second loop, it holds the sales value. Since these values do not have keys, there is no other way to reference them directly.

A more concise code snippet achieving a similar outcome:

JObject jo = JObject.Parse(json);
        for (int i = 0; i < jo.Count; i++)
        {
            var jList = from values in jo["Project"][i]["Statistics"]
                        select values;                
            foreach (var stat in jList)
            {
                //stat appears as {["20140722", 32.22]}
            }

        }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting the PHP encoded Postgresql query result into a stringified array

I have a SQL query that transforms the result into JSON format. SELECT 'FeatureCollection' As type, array_to_json(array_agg(f)) As features FROM ( SELECT 'Feature' As type, ST_AsGeoJSON(geom)::json As geometry, ro ...

What is the process for bringing data from a REST API into a SQL Server database?

My REST API delivers a JSON-formatted response that looks like this: { "Employees" : [ { "userId":"romin", "jobTitleName":"Developer", "emailAddress":"<a href="/cdn-cgi/l/email-protection" class="__cf_ema ...

Error -1 with JSON key

I've been tirelessly seeking the solution to this issue, but it eludes me. My goal is to retrieve the value by index of a JSON string. Despite the matching key, I'm getting -1 for the index. All I want is the value "Ethan" for the key username. ...

Styling Result received from Web API call within an array

I am currently working on a function call that retrieves the result of an SQL query in an array format. app.get('/alluser', (req, res) => { console.log("All Users") user.getAllUsers(function (err, result) { if (!err) ...

Unable to perform JSONArray conversion in Java (Android)

I'm encountering an issue when trying to execute the code below as it keeps throwing an Exception. Code try { JSONObject jsonObject = new JSONObject(result); JSONArray jsonArray = jsonObject.getJSONArray("current"); } catch (JSONExcepti ...

Async AJAX request and asynchronous C# controller function

Consider the following situation. I have an ajax request call in my ExtJS application. By default, the ajax call is set to asynchronous (async: true). On the server side, I also have a method that returns a Task, indicating it is also asynchronous. What i ...

Verify the occurrence of a search result and if it appears more than once, only show it once using JavaScript

Hello all. Currently, I am developing an online users script using NodeJS and SocketIO. The functionality works fine, however, I am encountering an issue where if a user connects from multiple browsers, windows, or devices, it displays duplicate results li ...

Utilizing AngularJS to organize JSON data and display it in a table format

I currently have a JSON file that I am extracting data from using Angular.js. However, I would like to format the output in a table as depicted below. Here is my HTML and JavaScript code where I am retrieving the JSON data using Angular: https://i.stack. ...

Converting personal injury claims into configuration maps with the help of jq

Here is my input: { "apiVersion": "apps/v1", "kind": "Deployment", "spec": { "template": { "spec": { "containers": [ { "volum ...

Converting PHP JSON data (without keys) to Java

I have received JSON data: [["13021031","icon_nopic.png"]] This data does not contain a specific "key". Despite trying various methods, including Gson, I am unable to parse the data because it lacks a key. Can anyone suggest a solution to this issue? Th ...

Tips for sharing JSON data between JavaScript files

Here is the initial script setup to utilize static .json files for displaying and animating specific content. The code provided is as follows: var self = this; $.getJSON('data/post_'+ index +'.json', function(d){ self.postCa ...

Steps for accessing a specific key value from a hashmap with a freemarker template

In the code below, I am setting key values into a hashmap within the main function. How can I format the freemarker template to only read one specific key value instead of iterating through the entire list? import freemarker.template.TemplateException; ...

What is the best way to send a List in the model as a parameter for an AJAX request?

I'm currently using MVC 4 ASP.net with Razor views and I have an issue with refining my search results using AJAX calls. The current approach involves creating methods in the controller that include all the search filters, which has resulted in a meth ...

The JSON data did not fully transfer into my AngularJS application

I wrote the code to display country details, but I am only getting partial information from the JSON. I am only able to fetch the country name and population in the output. Could there be an issue with the syntax? <!DOCTYPE HTML> <html ng-app= ...

Retrieve information from deeply nested JSON within the remoteMessage object in Firebase

I've been working on developing a messaging application using Swift. After configuring Firebase Cloud Messaging, I was able to successfully receive data on my device. func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMes ...

Instructions on dynamically adding a control with an event handler to an update panel and ensuring the event handler triggers a post back using AJAX

I've hit a roadblock with my attempt to make this work. Despite trying various solutions, I can't seem to get it right. Is it possible that what I'm aiming for is just not achievable? Here's the code in the aspx file: <asp:Content ...

retrieve content within an iframe via ajax

I currently have an iframe set up on the server side like this: <iframe frameborder="0" runat="server" style="width: 100%; height: 700px; background-color: #bacad3;" id="I1" name="I1" src="Page.aspx"></iframe> and I update the content dynamic ...

Python OSError: [Errno 9] Issue with file descriptor encountered upon attempting to open large JSON file

Recently, I attempted to process a large json file (the Wikipedia json dump) in Python by reading it line by line. However, I encountered the following Error: Traceback (most recent call last): File "C:/.../test_json_wiki_file.py", line 19, in ...

Discovering strings within strings on the Android platform

In my current project, I am dealing with a lengthy JSON text that contains movie titles. I need to extract these titles from the following pattern: ((((((( .","title":" AND ","type":" ))))))) After researching other solutions, I came across one appro ...

Error: The JSON file cannot be located by the @rollup/plugin-typescript plugin

I have recently set up a Svelte project and decided to leverage JSON files for the Svelte i18n package. However, I am facing challenges when trying to import a JSON file. Although the necessary package is installed, I can't figure out why the Typescri ...