What is the best way to iterate through all values in a LinkedTreeMap with the keys as Strings and the values as

I am facing an issue where I have a JSON file and all the data is stored in a LinkedTreeMap<String, Object>. The problem arises when one of the JSON fields becomes complex:

{
    "val1": "1",
    "val2": "2",
    "val3": {
        "embVal1": "emb1",
        "embVal2": emb2
    },
    "val4": "4"
}

For example, if val3 is a complex field, then mapping it with an Object type will require transforming it into another

LinkedTreeMap<String, Object>
, resulting in my structure to look like
LinkedTreeMap<String, LinkedTreeMap<Sting, Object>>
.

If val3 contains other complex objects within it, then the value of Object type will also need to be transformed into a new

LinkedTreeMap<String, Object>
, continuing recursively as we delve deeper into the JSON tree.

The challenge now is how can I efficiently traverse all embedded nodes in a structure like this?

Answer №1

Here is the code snippet that I put together without much focus on performance, but it functions effectively

AppTest.java

public class AppTest {
    
    @Test
    public void testApp() {
        LinkedTreeMap<String, Object> node = new LinkedTreeMap<>();
        LinkedTreeMap<String, Object> node2 = new LinkedTreeMap<>();
        LinkedTreeMap<String, Object> node3 = new LinkedTreeMap<>();
        
        node2.put("embembVal1", "embemb1");
        node2.put("embembVal2", "embemb2");
        
        node3.put("embVal1", "emb1");
        node3.put("embVal2", node2);
        
        node.put("val1", "1");
        node.put("val2", "2");
        node.put("val3", node3);
        node.put("val4", "4");
        
        MyJson json = new MyJson();
        json.read(node);
        
        System.out.println(MyJsonBuilder.build());
    }

}

MyJson.java

public class MyJson {
    
    public void read(LinkedTreeMap<String, Object> node) {
        MyJsonBuilder.append("{");
        
        for(Entry<String, Object> set : node.entrySet()) {
            if(!getInstanceType(set.getValue())) {
                jsonFormat(set.getKey(), set.getValue());
            } else {
                new MyJson().read( (LinkedTreeMap<String, Object>) set.getValue() );
            }
        }
        
        MyJsonBuilder.append("}");
    }
    
    private void jsonFormat(String k, Object v) {
        MyJsonBuilder.append( String.format("\"%s\":\"%s\"", k, v) );
    }
    
    private boolean getInstanceType(Object obj) {
        if(obj instanceof LinkedTreeMap) return true;
        else return false;
    }
   
}

MyJsonBuilder.java

public class MyJsonBuilder {
    
    private static StringBuilder jsonBuilder = new StringBuilder();
    
    public static void append(String node) {
        jsonBuilder.append(node);
    }
    
    private static String format(String json) {
        String adjustedjson = json;
        if (adjustedjson.contains("\"\"")) adjustedjson = adjustedjson.replaceAll("\"\"", "\",\"");
        if (adjustedjson.contains("}\"")) adjustedjson = adjustedjson.replaceAll("}\"", "},\"");
        
        return adjustedjson;
    }
    
    public static String build() {
        return format(jsonBuilder.toString());
    }
    
}

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

Learning to extract information from a JSON file with various key and value combinations

I am facing a challenge with my JSON data file, which contains UserIDs as keys and Passwords as values. My goal is to use JavaScript for validation by reading this JSON file. The structure of my JSON is as follows: IDsNPass = '[{"A":"A15"},{"B":"B15" ...

Defining JSON Schema for an array containing tuples

Any assistance is greatly appreciated. I'm a newcomer to JSON and JSON schema. I attempted to create a JSON schema for an array of tuples but it's not validating multiple records like a loop for all similar types of tuples. Below is a JSON sampl ...

Is there a way to eliminate curly braces from JSON strings with a regular expression?

Hello, I am working with a JSON file and I need to manipulate the content of the chapters array. Specifically, I want to remove the curly braces from inside the strings but only if they contain more than three words (two spaces). Is it achievable using Reg ...

A guide on organizing nested JSON objects in JavaScript

I am currently using JavaScript to retrieve JSON data that looks like this: [{ "data": { "serialNumber": "12345678", "loopCount": 2, "temperature3": 22.74921781259558, "temperature2": 21.459065450414467, "temper ...

Looking for a simple method to link JSON data to an svg element through Javascript?

Looking to harness the power of SVG for a basic graph creation, but uncertain about the process of assigning JSON data dynamically using a 'for loop' to draw rectangles within SVG. Seeking guidance on setting up 1 loop to assign each value for dr ...

Automatically populate the options of a dropdown menu using jQuery

I am a beginner in the world of Javascript, JSON, and jQuery. I am seeking some guidance as I navigate through this new territory. On my JSP page, there is a drop down list that needs to be populated with content when the page loads. To achieve this, I hav ...

Guide on creating a JSONP request

My goal is to perform cross-site scripting. The code snippet below shows the jsonp method, which appears to fail initially but succeeds when switched to a get request. I am trying to achieve a successful response using the jsonp method. I have confirmed th ...

How can you sort an array based on a shared object property using Angular.js?

I've been grappling with this issue for a while now. My app receives data about individuals in JSON format: "people": [ { "name": "Ivan", "city": "Moscow", "country": "Russia" }, { "name": "John", ...

Retrieving Data from a JSON File in ASP.NET MVC 4

After diving into learning ASP.NET MVC 4, I dabbled in some small projects... On my index page, my goal is to fetch a JSON file containing data and showcase it on the main page. In basic HTML and JavaScript, I utilize ajax for fetching or posting JSON da ...

Changing an Array into JSON format using AngularJS

I am attempting to switch from a dropdown to a multiselect dropdown. <select name="molecularMethod" class="form-control" ng-model="request.molecularMethod" multiple> It is functioning properly. However, when items are selected, it generates an arra ...

Failing to send contact information using JSON in PHP

I attempted to transmit JSON data to PHP for email processing, but encountered an issue where the process veered into the 'else' condition during debugging. Here is the code snippet: HTML <form id="cbp-mc-form" class="cbp-mc-form" method="po ...

Returning a JSON representation of a JavaScript object

In the process of working on a script, I encountered a situation where an $.ajax call had to invoke a function upon success, returning a JavaScript object in JSON format [object object]. However, despite being able to return a well-formatted string, access ...

Ruby on Rails and JSON: Increment a counter with a button press

How can I update a count on my view without refreshing the page when a button is clicked? application.js $(document).on('ajax:success', '.follow-btn-show', function(e){ let data = e.detail[0]; let $el = $(this); let method = this ...

Encountering a missing value within an array

Within my default JSON file, I have the following structure: { "_name":"__tableframe__top", "_use-attribute-sets":"common.border__top", "__prefix":"xsl" } My goal is to add values by creating an array, but I am encountering an issue where my ...

Importing JSON data into JavaScript

For the past few hours, I've been attempting to load a JSON file into JavaScript to feed map coordinates to the Google Maps service. Unfortunately, my script is incomplete and I cannot obtain any results. Here's what I have so far: <script&g ...

Troubleshooting problems with displaying views due to asynchronous $http.get calls in AngularJS

Within my application, I am utilizing two separate API calls. The initial call retrieves a catalog of services along with their unique ID's. Subsequently, once the ID information is acquired, a second call is made to retrieve pricing data for each cor ...

JavaScript and JSON interchangeably, the first AJAX response should be rewritten by the second response

I am facing an issue with my code: I have two ajax calls being made on window.load, and it seems like the response from the second AJAX call is overwriting the response from the first one before my function can process it. I'm not sure where I'm ...

use the fetch api to send a url variable

I'm struggling to pass a URL variable through the API fetch and I can't seem to retrieve any results. As a newcomer to Javascript, any help is greatly appreciated. //Get IP address fetch('https://extreme-ip-lookup.com/json/') .then(( ...

The JSON array retrieved from the $http.GET request is coming back as undefined, which is not expected

Presenting my code below: function gatherDataForGraph(unit, startTs, endTs, startState, endState){ points = []; console.log('/file/tsDataPoints/'+unit+"?startDate="+startTs+"&endDate="+endTs+"&startState="+startState+"&endState="+en ...

Error Occurred while Uploading Images using Ajax HTML Editor with JSON Data

I am facing an issue with my AJAX HtmlEditorExtender, specifically when trying to upload an image. The error message I receive is as follows: JavaScript runtime error: Sys.ArgumentException: Cannot de-serialize. The data does not correspond to valid JSON. ...