Transform a collection of hierarchical strings into JSON using C#

I have a series of strings that represent hierarchical information and are separated by hyphens (3 hyphens indicate separation). My goal is to convert this list into a JSON format so that I can link it to a tree control component.

I am in search of a C# sample code for achieving this task.

Here is an example of how the list might look like (this is just a snippet and it could potentially extend up to 7 levels deep, but you'll get the concept):

Automotive Electronics
Automotive Electronics---Body Electronics
Automotive Electronics---Body Electronics---Access Control Systems
Automotive Electronics---Body Electronics---Body Control Modules
Automotive Electronics---Driver Information
Automotive Electronics---Driver Information---Clocks
Automotive Electronics---Driver Information---Compass Systems
Automotive Electronics---HomeL
Automotive Electronics---Infotainment & Connectivity
Automotive Electronics---Infotainment & Connectivity---Handsfree Systems
Automotive Interiors
Automotive Interiors---Door Panels
Automotive Interiors---Floor Consoles
Automotive Interiors---Headliners & Overhead Systems
Automotive Interiors---Overhead Consoles
Automotive Seating
Automotive Seating---Complete Seats
Automotive Seating---Complete Seats---SuperThin Seats

Answer №1

The key strategy involves organizing the strings into a hierarchical tree structure. The following code snippet in LinqPad demonstrates this process. While the direct output may not be readily usable client-side, it can be easily customized to suit your needs.

void Main()
{
    var rootNode = new Node("root");
    foreach(string s in new[] {"Automotive Electronics",
        "Automotive Electronics---Body Electronics",
        "Automotive Electronics---Body Electronics---Access Control Systems",
        "Automotive Electronics---Body Electronics---Body Control Modules",
        "Automotive Electronics---Driver Information",
        "Automotive Electronics---Driver Information---Clocks",
        "Automotive Electronics---Driver Information---Compass Systems",
        "Automotive Electronics---HomeL",
        "Automotive Electronics---Infotainment & Connectivity",
        "Automotive Electronics---Infotainment & Connectivity---Handsfree Systems",
        "Automotive Interiors",
        "Automotive Interiors---Door Panels",
        "Automotive Interiors---Floor Consoles",
        "Automotive Interiors---Headliners & Overhead Systems",
        "Automotive Interiors---Overhead Consoles",
        "Automotive Seating",
        "Automotive Seating---Complete Seats",
        "Automotive Seating---Complete Seats---SuperThin Seats"})
    {
        AddNodes(rootNode, s.Split(new[] {"---"}, StringSplitOptions.RemoveEmptyEntries));
    }
    new JavaScriptSerializer().Serialize(rootNode.Nodes).Dump();
}

public void AddNodes( Node parentNode, string[] names)
{
    if (names.Any())
    {
        var node = parentNode.AddNode(names.First());
        AddNodes(node, names.Skip(1).ToArray());
    }
}

public class Node
{
    public Node(string name)
    {
        Name = name;
        Nodes = new List<Node>();
    }

    public Node AddNode(string name)
    {
        if (!this.Nodes.Select(n => n.Name).Contains(name.Trim()))
        {
            //name.Dump(this.Name);
            this.Nodes.Add(new Node(name.Trim()));
        }
        return this.Nodes.Where (n => n.Name == name).First();
    }

    public string Name { get;set;}
    public List<Node> Nodes { get; set; }
}

Output:

[{"Name":"Automotive Electronics","Nodes":[{"Name":"Body Electronics","Nodes":[{"Name":"Access Control Systems","Nodes":[]},{"Name":"Body Control Modules","Nodes":[]}]},{"Name":"Driver Information","Nodes":[{"Name":"Clocks","Nodes":[]},{"Name":"Compass Systems","Nodes":[]}]},{"Name":"HomeL","Nodes":[]},{"Name":"Infotainment & Connectivity","Nodes":[{"Name":"Handsfree Systems","Nodes":[]}]}]},{"Name":"Automotive Interiors","Nodes":[{"Name":"Door Panels","Nodes":[]},{"Name":"Floor Consoles","Nodes":[]},{"Name":"Headliners & Overhead Systems","Nodes":[]},{"Name":"Overhead Consoles","Nodes":[]}]},{"Name":"Automotive Seating","Nodes":[{"Name":"Complete Seats","Nodes":[{"Name":"SuperThin Seats","Nodes":[]}]}]}]

(Please note that you need to import specific namespaces in LinqPad for the JavaScriptSerializer to work properly).

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

Halted: Android Json Retrieval from URL Ceases

Recently, I began working on extracting data from a JSON OpenData source and visualizing it using my smartphone. I followed a tutorial which proved to be quite helpful. The url where I retrieved the data is: http:// + api.learn2crack.com/android/json/ ...

When trying to log the parsed JSON, it unexpectedly returns undefined even though it appears to be in good

Everything was working fine until a couple of days ago. Let's consider this as my PHP script: echo json_encode(array('stat'=>'ok')); I am sending an AJAX request to this script: $.post(base_url+'line/finalize/', {t ...

Attempting to showcase information on the Angular frontend

When attempting to retrieve the Street name, I am seeing [object Object]. What is the optimal approach for displaying JSON data on the client side? I managed to display a street name but struggled with other components. How can I access the other elements ...

What could be the reason for the extra tags being returned by YQL?

Currently, I am executing a query in the YQL console with the following data: select * from html where url='http://www.motorni-masla.net/index.php?main_page=product_oil_info&cPath=140&products_id=294&zenid=c8281021bbfed454176247900b3b9d4a ...

Creating a clone of JSON for use as a template

I am working with a json template that I fill with product data. Here is an example of the json structure: // product template $scope.productAttributes = { "Code": null, 'Attributes': {} }; When a user inputs produ ...

I keep encountering an issue with getJson

A snippet of my JavaScript code retrieves a JSON object from a URL. Here is the portion of the code in question: <script> $(document).ready(function(){ $("button").click(function(){ $.getJSON('url_address', {}, function(data) { ...

The WebMethod isn't being triggered during debugging

Recently, I have been facing an issue while trying to insert data using jQuery. Previously, I had successfully performed this task, but after a long break, I encountered a problem. Upon debugging with the browser, I noticed that the Ajax call was not being ...

Support needed to extract MQTT JSON data and convert it into individual entities using a

I am currently setting up my deebot robot to work with MQTT through Node-Red integration. I have successfully configured everything in Node-Red, but I am facing an issue with splitting values from the MQTT message. Here is a snippet of what I receive (mult ...

I am in search of understanding the criteria for determining when an ISearchContext can be considered

I've been scouring different sources for information on this particular topic, and while I did find a similar answer here, I'm looking for a bit more detail. Here's my code: var element = myWebDriver.FindElement("User_Login"); var finalele ...

The regex_replace function disregards any content that follows a NULL value

Within my database table "ticket_full", there is a json type column titled "service_id" from which I want to extract data into 3 separate columns. Here is an example of the structure: [{"position":"1","typeid":"ROUTNAME&q ...

Is it really impossible to post complex JSON parameters with Restangular?

Is it possible to send a complex JSON object to a PUT route using Restangular? Restangular.one('model3ds', model.uuid).put( api_key: "blabla" model3d: { is_public: true } ) However, the data sent by Restangular appears as: ...

Converting a JSON array of key-value pairs to a Java HashMap using the Jackson JSON library

Currently, I am delving into my first Java Json parser library which happens to be Jackson JSON. I'm in the process of converting a List of ID/NOTE into a HashMap list as a Java Object. The structure of my Json input appears as follows: var basketL ...

Converting JSON data into a Pandas dataframe

I am encountering an issue with converting JSON formatted data to a Pandas dataframe. The JSON data I have is structured as shown below and is stored in the variable active_assets - Asset({ 'class': 'us_equity', 'easy_to_borr ...

Tips for optimizing command execution speed while using selenium?

Is there a way to adjust the speed at which the mouse moves in selenium? I came across the DefaultSelenium class, but it's not static and I'm unsure how to use it to set delays in specific webdrivers. Could someone please provide a helpful exam ...

What sets apart the browser/tab close event from the refresh event?

Can you help me understand the difference between a browser/tab close event and a refresh event? I've been researching this on Stack Overflow, but I'm still having trouble with it. My goal is to be able to log out a user through a server call whe ...

An error occurred in retrieving the server side props: Unexpected character '<' found in JSON data at position 0

I am currently working with next.js and I am trying to retrieve data from my data1.json file using getStaticProps(). However, I am encountering an error: FetchError: invalid json response body at http://localhost:3000/data/data1.json reason: Unexpected t ...

Encountering a 415 Unsupported Media Type error when making a post request to an ASP.NET Core API from an Angular application

Utilizing the code above in an Angular application: function Login(email, password, callback) { var GetAll = new Object(); GetAll.email = email; GetAll.password = email; $http({ url: "http://local ...

An unexpected error occurred when attempting to transform the data into a string, leading to

I have a PHP file that sends an array to my Android device. Upon receiving the data, it is converted to a string. I am then attempting to retrieve the associative array index created with PHP. Here's a snippet of the PHP code: if(mysql_num_rows($quer ...

Error Message: An error occurred due to an unset object reference when utilizing the Update

Encountered the error message "Object reference not set..." while debugging my code. Upon investigation, I discovered that the issue lies within the UpdatePanel. Removing it resolved the problem, but unfortunately, it's necessary to prevent page reloa ...

PHP is consistently failing to decode a JSON object generated by JavaScript, with the error code always being 4

In my JavaScript code, I am working on creating a map of key and value pairs. To achieve this, I create an object and store it in a hidden textarea. My intention is to retrieve the data using PHP, decode the object, and ultimately save it to a database. Th ...