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

Utilize the jQuery function as a callback argument

There is a jQuery plugin that I am currently working on: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head><title></title> <script type="text/javascript" sr ...

Obtain the value of v-model in a child component within VueJS

In my Vuetify App, I have implemented a Vue2Editor using a custom component called text-editor. Here is how it looks: <vue-editor :value="text" @input="updateText" ></vue-editor> The props for this component are defined as follows: props ...

Navigate within a div using arrow keys to reposition another div

As a newcomer to JavaScript, I am facing some challenges. My goal is to use arrow keys to move a small div inside a larger div. However, the code below is not functioning as expected. Here is the HTML and CSS: <div id="rectangle"> <div id="s ...

Using VueJS to Bind an Array of Integer Values to Checkbox Models

I encountered a discrepancy between VueJS 1.0 and VueJS 2.0 regarding checkbox behavior. In VueJS 1.0, when binding checkboxes to a list of integers in v-model, the integers do not register as checked attributes. Below is the HTML code snippet: <div i ...

Enhance the display in Angular2

Just started working with Angular 2 and I've encountered a problem. I have an API that loads a JavaScript file in my project. The issue is, I need to use this JS file and cannot modify it. Essentially, this JS file has some methods that make AJAX call ...

Harnessing the power of express middleware to seamlessly transfer res.local data to various routes

I am in the process of implementing a security check middleware that will be executed on the specific routes where I include it. Custom Middleware Implementation function SecurityCheckHelper(req, res, next){ apiKey = req.query.apiKey; security.securi ...

Leverage the Power of JSON Data Manipulation in WordPress with Angular JS and the WordPress JSON

After testing code in this particular post and making some adjustments, I encountered an issue with obtaining a JSON object from the API of my blog created using the WordPress JSON plugin. URL of API from BLOG (NOT FUNCTIONING): URL from W3C example (WO ...

The object of type 'AttrList' cannot be serialized as JSON

class SearchSuggest(View): def get(self, request): key_words = request.GET.get('s','') re_datas = [] if key_words: s = JobType.search() s = s.suggest('my_suggest', key_words, completion={ ...

Validate form for radio group

Hello Experts, I am currently working on developing a form that includes a JavaScript validation function for a radio group. The main objective is to have a division pop up when either "Monday" or "Tuesday" is checked, and no popup when "None" is selected ...

How to implement PayPal integration in PHP

I am currently working on integrating the paypal payment system into a website dedicated to pet adoption. Initially, I had a basic code structure that was functional. However, after making some modifications and additions to the code, it no longer redirect ...

eliminating the xml labels in a json dataset

I'm curious about converting database data to JSON format using an asp.net web service. However, the data I receive comes with XML tags that I need to remove in order to work effectively with it. The structure of the data is as follows: ?xml version= ...

Capybara's attach_file function is not properly activating the React onChange handler in Firefox

Currently, I am conducting tests on the file upload feature of a React-built page. The page includes a hidden file input field with an onChange event listener attached to it. Upon selecting a file, the onChange event is triggered and the file is processed ...

Converting Currency Codes to Symbols using PHP JSON

My goal is to develop a system that can accurately return the official currency symbol based on the input of a 3-letter currency code. For example, if the function receives 'USD', it should return the '$' sign, and likewise for all curr ...

JavaScript Money Exchange

Can currency be recalculated using JavaScript or jQuery? For instance: <div id="price">$99.00</div> Could become <div class="gbp" id="price">£63.85</div> If a class of "GBP" was added to the div tag? ...

When the limit is set to 1, the processing time is 1ms. If the limit is greater than 1, the processing time jumps to

Here is the MongoDB Native Driver query being used: mo.post.find({_us:_us, utc:{$lte:utc}},{ fields:{geo:0, bin:0, flg:0, mod:0, edt:0}, hint:{_us:1, utc:-1}, sort:{utc:-1}, limit:X, explain:true }).toArray(function(err, result){ ...

What is the best way to keep the calendar of a Datepicker always visible while still being able to select a date easily?

When I write my code, the calendar only appears when I press the TextBox. I attempted to place the datepicker in a <div>, but then I was unable to retrieve the selected date. @model Plotting.Models.CalendarModel @using (Html.BeginForm("Calendar", "H ...

Avoiding code duplication in Angular: tips for optimizing functions

Is there a way to avoid repeating the same for loop for a second variable and use only one? I'm trying to apply the "Don't repeat yourself" method here. Should I consider using an array? JS: var app=angular.module('xpCalc', []); app.c ...

Tips for keeping the app on the same route or page even after a refresh

I'm currently diving into the world of React and am in the process of constructing a CRUD application. I've successfully created multiple pages that utilize react-router-dom for navigation with authentication. The pages are accessible only to log ...

Troubleshooting problem with infinite scrolling in AngularJS with Ionic framework

I recently created a webpage with an infinite scroll page load more script using Ionic AngularJS. However, I encountered an issue where the page restarts from the beginning once it reaches the bottom. Below is the HTML code snippet: <ion-content class ...

Using Logback in Java to show the outcome of the execution (success / failure)

I am currently utilizing Logback for logging in my Selenium Webdriver project. I am looking for a way to log the test status (whether it passed or failed) at the end of each test, so it is easier to identify which tests have failed when reviewing the logs. ...