What is the best way to transfer a JSON object from Java to JavaScript?

I've been struggling to pass data from my Spring controller to JavaScript, but I haven't had any success so far. Would using ajax be the best approach for this task? Can you provide me with some hints on how to achieve this effectively?

In my controller, I am attempting to pass the data:

@RequestMapping(value = "/map", method = RequestMethod.GET)
public String map(ModelMap model) {

...

model.addAttribute("trackpoints", json);


return "map";

}

where 'json' is a Gson object (JsonObject) containing:

{"trackpoints":[{"latitude":52.390556,"longitude":16.920295},
{"latitude":52.390606,"longitude":16.920262}]}

In my JSP file, I have:

<script type="text/javascript>

var myJSON = {};

myJSON = ${trackpoints};

document.writeln(myJSON.trackpoints);

</script>

However, the result appears as:

[object Object],[object Object]

To elaborate further:

I want to use the Google Maps API to display a map and draw path coordinates using multiple latitude and longitude points. I believe using JSON would be more efficient than a list, but I could be mistaken.

I attempted to modify code from the documentation - in the code below, I tried to replace hardcoded coordinates with a loop that extracts values from the JSON object.

<script type="text/javascript>
function initialize() {
    var myLatLng = new google.maps.LatLng(0, -180);
    var myOptions = {
        zoom : 3,
        center : myLatLng,
        mapTypeId : google.maps.MapTypeId.TERRAIN
    };

    var map = new google.maps.Map(document.getElementById("map_canvas"),
            myOptions);
    var flightPlanCoordinates = [
            new google.maps.LatLng(37.772323, -122.214897),
            new google.maps.LatLng(21.291982, -157.821856),
            new google.maps.LatLng(-18.142599, 178.431),
            new google.maps.LatLng(-27.46758, 153.027892) ];
    var flightPath = new google.maps.Polyline({
        path : flightPlanCoordinates,
        strokeColor : "#FF0000",
        strokeOpacity : 1.0,
        strokeWeight : 2
    });

    flightPath.setMap(map);
}
</script>

I hope this explanation clarifies things :)

Answer №1

myJSON.trackpoints is an array consisting of two objects. To represent it in HTML, you can use the following approach:

function displayCoordinates(coords) {
    document.writeln('<div>lat = ' + coords.latitude);
    document.writeln(', lon = ' + coords.longitude + '</div>');
}

int length = myJSON.trackpoints.length;
for (int index = 0; index < length; index++) {
    displayCoordinates(myJSON.trackpoints[index]);
}

By the way, JSON comes in handy when dealing with AJAX requests. However, for regular requests, it's recommended to use plain Java objects in the model. For instance:

Spring Controller:

List<Coordinate> trackpoints = ...
model.addAttribute("trackpoints", trackpoints);

JSP:

<c:forEach items="${trackpoints}" var="coord">
    <div>lat = ${coord.latitude}, lon = ${coord.longitude}</div>
</c:forEach>

In this case, the Coordinate class should have methods like getLatitude() and getLongitude(). The method in the Spring controller can be used for both regular and AJAX requests by utilizing a JSON encoder such as Jackson, along with the ContentNegotiatingViewResolver.

Answer №2

Check out this link for more information: http://jsfiddle.net/AHue8/4/

The key takeaway here is the importance of specifying which element within the trackpoint object you want to display, and controlling how it appears in the browser. Since a "trackPoint" is not a simple data type (it's an object with latitude and longitude properties), the browser needs guidance on how to handle it.

Answer №3

My situation was similar: I needed to pass a list of Java objects from a Spring Boot controller to JavaScript code (to be treated as JSON objects). After some research, I came up with a solution:

Using Java

First, retrieve the list of MyObject, convert it into a JSON string, and add it to the model. Here is an example of how to achieve this:

import com.google.gson.Gson;

@Service
public class MyService {

    private static final Gson GSON = new Gson();
    
    
    public void getData(final Model model) {
        List<MyObject> myObjectList = getObjects...
        model.addAttribute("myObjectListAsJsonText", GSON.toJson(myObjectList));
    }
    
}

In the JSP/HTML Page (Not in a Separate JS File)

Add a script block to retrieve the JSON representation of the MyObject list and convert it into a JSON array that can be processed by JavaScript:

<title>MyApp | Main page</title>
<link rel="shortcut icon" href="resources/img/favicon.ico">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script  th:inline="javascript">
    var myObjectListAsJson = '${myObjectListAsJsonText}';
    var myObjectJsonArray = JSON.parse(myObjectListAsJson);
</script>

In Any Separate JavaScript file on the Same Page

You can access the global variable myObjectJsonArray, which contains the JSON array of MyObject items, like so:

function processMyObjectJsonArray() {
    for (var index = 0; index < myObjectJsonArray.length; index++) {
        var myObjectJsonItem = myObjectJsonArray[index];
        console.log("Accessing the ID attribute of an item in the MyObject array:" + myObjectJsonItem.id);
    }
}

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 is the purpose of the execute_script() function in Selenium?

browser.execute_script("window.open('about:blank', 'tab2');") browser.switch_to.window("tab2") browser.get('http://bing.com') While exploring ways to open a new tab using Selenium in Python, I found the ab ...

The connection to MongoDB is failing due to an incorrect URI

I tried setting up mongoDB on my node server and referred to the official MongoDB documentation. Here are the details of my setup: MongoDB version: 4.4.3 Node.js version: v15.7.0 I copied the starter code from MongoDB and here is what I used: const { Mon ...

Can anyone help me get my carousel to work properly?

I am facing a carousel problem in my personal exercise project. I have gathered HTML, CSS, and JavaScript from the internet and am attempting to integrate them all together. //Sidebar script start $(document).ready(function () { var trigger = $(&apo ...

Is your jQuery search scope correctly restricted?

Upon coming across this code snippet, I can't help but wonder if it's merely limiting the scope or selecting both elements simultaneously. container = jQuery("#test", parent.document); jQuery("param[name=scale]", another.object) Would anyone b ...

"errorDescription": "The function index.handler is either undefined or not exported",

My current project involves transferring data from a Particle device to my MySQL database on AWS. I am following this guide for reference: https://medium.com/@mohkil87/how-to-store-data-generated-by-particle-devices-to-aws-rds-mysql-using-webhooks-343bc780 ...

Locate the entries containing the minimum and maximum values in a column, then display several results

I am attempting to extract the "created-at" data based on the minimum and maximum values I retrieve. Below is a sample JSON structure: { "channel": { "id": "xxxxxxx", "field1": "A", "created_at": "2021-06-16T19:06:15+07:00", ...

Modify the text tone within a specific cell

Welcome to my unique webpage where I have implemented a special feature. The text highlighted in red represents the unique identifier for each individual cell. Interestingly, below there is an input field containing the code "0099CC", which corresponds to ...

Implementing Angular checkbox repetition controlled from an external controller

I'm looking to streamline my controller by setting a variable from outside the controller to populate my checkbox list. Can this be done? Check out my current code snippet here: http://jsfiddle.net/ilmansg/Lx37kr3e/1/ VIEW HTML <div ng-controlle ...

Handling Ajax response in datatable

While working on a project that involves integrating DataTables and Excel files, I encountered the challenge of uploading an Excel file and displaying its contents using DataTables. Despite my search for a JavaScript library that could parse the Excel fi ...

Creating elegant Select Dropdown Box in AngularJS without relying on images

I am currently working on an angular page and have implemented a dropdown with ng-Options to fetch and set values successfully. However, I am now looking to enhance the appearance of this dropdown. After exploring options like ui-select, I realized that be ...

Activate the Chrome Extension that allows you to open a link in a new tab with just a middle click or regular click, without closing the popup

When I try to click a link in my extension popup and open it in a new tab using "middle click -> open link in a new tab", the popup closes. Is there a way to keep the popup open so I can click on multiple links from my extension without interruption? A ...

Send the typeahead object result from Angular to another function within the controller

In my current setup, I am utilizing the ui-bootstrap typeahead feature to fetch an object from an external API. Upon selecting the object, it triggers a callback function that stores the results in a separate function within my controller. The challenge l ...

iPhone 6 (iOS) users may face compatibility issues with iframe and fancy box features

I am currently learning how to use jQuery and the fancybox library. In my Angular 1 and Ionic project, I have successfully implemented fancybox with an iframe. Everything works perfectly on browsers and Android devices, but on iOS, a loader icon appears an ...

Insert metadata tag into the head element of the parent iframe

I am looking to insert a meta tag element into the head element of an Iframe parent. I attempted window.parent.$('head').append('sometext'); This method worked when the source file and iframe file were in the same folder, however it d ...

What is the best approach to display a fluctuating price depending on specific options chosen in Next.js?

When working with 2 different select tags and rendering images based on the selection, I also want to display a price determined by the options chosen. For instance, selecting "Your Current Division" as Iron and "Your Desire League" as Bronze/Silver/Gold s ...

Utilizing ng-model in AngularJS to add data to an array in Mongoose and MongoDB

I am currently utilizing ng-model to input data into my MongoDB. Is there a method to utilize ng-model to insert data into an array within MongoDB? answers is an array that should include 4 strings entered by the user. I attempted adding [0], [1], [2], [3] ...

Receiving constant errors on Search Input in React: continuously encountering the error "Cannot read property 'value' of undefined."

Attempting to incorporate the < ChipInput /> element from https://github.com/TeamWertarbyte/material-ui-chip-input. Using material-UI react component, my current setup includes: A functional search input bar. When an artist's name is typed, it ...

Unlocking Node.js packages within React JS is a seamless process

Currently, I am developing a React Serverless App with AWS. I am looking for ways to incorporate a Node JS specific package into the React JS code without requiring Node JS on the backend. One package that I need access to is font-list, which enables list ...

Encountering an error with an undefined property while trying to extract information from a JSON string

Here is the JSON string I have: { "data": [ { "id": "533513150124231", "created_time": "2015-02-27T05:23:02+0000", ... }, { "id": "533911933417686", "created_time": "2015-02-28T07:18:09+0000", ... }, { "id": "533471226795090", "created_tim ...

What is the best method for invoking ajax requests from a service in AngularJS?

I am working on an Employee controller that includes properties such as Id, Name, and Specification. I have created an Employee service which makes an ajax call to retrieve a list of employees. However, every time I make the call, I receive an empty resp ...