Tips for generating nested elements in JSON and Java, alongside accessing the subitem values in JavaScript

By implementing this code, I was able to create the following structure

 int n=3;
        String json []= new String [n];       
        try {
            JSONArray js = new JSONArray();
            ArrayList<String> ciudades;
            ciudades = new ArrayList<String>();
            ciudades.add("tokio");
            ciudades.add("madrid");
            ciudades.add("santiago");
                JSONObject j;
            for (int x = 0; x < ciudades.size(); x++) {
                ArrayList<Integer> temp;              
               temp = new ArrayList<Integer>();
               for(int z=0;z<6;z++){
                  int temperatura = x+z;
                   temp.add(temperatura);
               }
                j = new JSONObject();
              j.put("name", ciudades.get(x));
               j.put("data", temp);
             js.put(j);
          }  
          json[0] = js.toString();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }finally {
            String valor="json1";
           request.setAttribute(valor, json[0]); 
           RequestDispatcher dispatcher = context.getRequestDispatcher("/datos.jsp");
           dispatcher.forward(request, response);

The generated structure looks like this

[
{"name":"tokio","data":[0,1,2,3,4,5]},
{"name":"madrid","data":[1,2,3,4,5,6]},
{"name":"santiago","data":[2,3,4,5,6,7]}
]

The desired structure that needs to be created is as follows

"paises": {
    "pais": [
      {"name":"tokio","data":[0,1,2,3,4,5]},
      {"name":"madrid","data":[1,2,3,4,5,6]},
      {"name":"santiago","data":[2,3,4,5,6,7]}
    ]
  }

When receiving the variables in JavaScript

var np= ${json1};
var datos = np;

To achieve the desired list structure and read the second level structure in JavaScript, further steps are needed.

Answer №1

Utilizing Gson library (along with lombok's @Data for support classes), and referring to the initial version of your question

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.ArrayList;
import java.util.List;

import lombok.Data;

public class Json {
    public static void main(String[] args)
    {
        final Wrapper wrapper = new Wrapper();
        final Paises paises = wrapper.getPaises();
        paises.getPais().add(Pais.of("Costa Rica", "San José"));
        paises.getPais().add(Pais.of("México", "DF"));
        paises.getPais().add(Pais.of("Argentina", "Buenos Aires"));

        final Gson gson = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gson.toJson(wrapper));
    }

    @Data
    private static class Wrapper {
        private Paises paises = new Paises();
    }

    @Data
    private static class Paises {
        private List<Pais> pais = new ArrayList<Pais>();
    }

    @Data(staticConstructor = "of")
    private static class Pais {
        private final String nombre;
        private final String capital;
    }
}

Result:

{
  "paises": {
    "pais": [
      {
        "nombre": "Costa Rica",
        "capital": "San José"
      },
      {
        "nombre": "México",
        "capital": "DF"
      },
      {
        "nombre": "Argentina",
        "capital": "Buenos Aires"
      }
    ]
  }
}

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

What are the steps to start up a NodeJS API using an Angular app.js file?

Currently, I am following various online tutorials to develop a web application using the MEAN stack and utilizing a RESTful API. I have encountered some challenges in integrating both the API server and Angular routes. In my project, I have a server.js f ...

The cube mesh is failing to render inside the designated div

I created a Torus and Cube Mesh in my scene, but I want the cube to be positioned at the bottom right corner of the screen. Here's what I tried: <div style="position: absolute; bottom: 0px; right:0px; width: 100px; text-align: center; "> & ...

Is there a different method similar to Textfield onChange that works like the HTML onChange attribute?

In my current setup, I have a Textfield component nested within other components where I pass a function pointer down to it as a prop. The challenge I'm facing is that the function responsible for passing the contents of the Textfield back up to the r ...

Change the source of another element when clicked

Check out the fixed version of previously broken code here I am facing challenges in changing an attribute on another element from a click function sniping $('#black').click(function() { $('#blackbox').slideToggle('slow&apos ...

changing the visible style of a div element using JavaScript

I'm having an issue with a link on my webpage that is supposed to show or hide a <div id="po" style="display:none;">some html</div> element. The first time I click the link, the div displays properly. However, after tha ...

Dynamically insert a new row into an HTML table using AJAX and refresh the table with .load method

I am facing an issue with my HTML table that loads data dynamically through a PHP snippet containing SQL queries. There is a Select option and a button on the table to add a new row, which triggers an AJAX procedure to send the data to PHP for insertion in ...

Exploring the Power of Destructuring Results in React.js with Apollo

I have been exploring the Apollo client for my project, and I encountered an issue with two of my query functions. The first query, which retrieves a list of users, is working perfectly fine. However, I am struggling to understand why my second simple quer ...

The URL does not contain the complete hash

I'm currently working on a gallery using Jquery Elastislide. var imageIndex = 0; if (window.location.hash) { var imageIndexStr = window.location.hash.replace('#',''); // removing # imageIndex = parseInt(imageIndexStr, 0) ...

The Rails JSON API is returning only the `created_at` and `updated_at`

I've recently set up a json API to retrieve bike data. The API is functional and returns json successfully, but I'm encountering an issue where it only includes the 'created_at' and 'updated_at' fields. This is what exists in ...

What is the best way to convert an object into an array of objects for use in a select search functionality

I am attempting to map key and value pairs into a single array in order to use them as selectsearch options. I have successfully mapped each item individually, but now I need to combine all the data into one array. How can I achieve this? Here is how I am ...

The content in tinymce cannot be edited or removed

Is there a method to prevent certain content within the tinyMCE Editor from being edited or removed? While I know that adding a class "mceNonEditable" can make a div non-editable, it can still be deleted. Is there a way to make it unremovable as well? ...

Executing code only after the completion of the .ajax function (outside of the .ajax function)

Working with an API, I successfully implemented the .ajax function but now need to access the data outside of that function. Attempting to use jQuery's .done function for this purpose has proved unsuccessful so far. Despite trying different solutions ...

Showing Sequelize validation errors in Express API: a comprehensive guide

In my Node.js/Express API with Sequelize ORM running MySQL, I have an Organization model that enforces a 2-100 character rule under validation. When this rule is violated in the first code snippet below, the err item from the catch block in the second code ...

Tips for halting the navigation bar when scrolling

Creating a Navigation Bar: <div class="navigation-bar"> <div class="item">Home</div> <div class="item">About us</div> <div class="item">Our Services</div> <div class="item">Contact us</div ...

How can I pull all data from an array using MongoDB query?

I have multiple arrays, but I am only interested in extracting the content related to "PIZZAS." Can anyone advise me on the appropriate query to achieve this? https://i.stack.imgur.com/wHolE.png ...

Having trouble with Next-Auth's signIn with Credentials feature in NextJS?

I have recently added the next-auth package to my new Next.js project. Despite following all the documentation for both Next.js and next-auth, I am still unable to resolve the issue. The problem I am encountering is as follows: I am trying to log in to my ...

I am looking to create a search functionality in this code that allows users to search using buttons (such as btn1, btn2, and btn3) and automatically hide any results that do not

Help needed with adding a search bar that allows searching between buttons btn1, btn2, and btn3. I've tried various codes focusing on TextView instead of buttons. Any assistance is appreciated. Let me know if more details are required. Code files (.j ...

Using Selenium WebDriver to handle Angular requests in Java

I am currently developing tests for an angular-based application and I find myself in need of assistance. The specific task at hand involves creating a mechanism that will wait until all pending requests within the application have been processed before pr ...

When using the HTML5 input type time in Chrome and the value is set to 00:00:00, it may not be fully completed

After inputting the html code below <input id="time_in" type="time" step="1" name="duration"> and setting the value in the browser to "00:00:00", everything appears fine. However, upon inspecting the console or submitting the form, the value gets ...

What is the best way to deserialize a JSON object into a Java POJO class?

I am working with a straightforward JSON statement that can be customized as needed, for example: { actor:{name:"kumar",mbox:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f746a727e6d5f78727e7673317c7072">[email&# ...