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

Ember - Initiate a GET request to access a list of trees from an API endpoint

I have a project that utilizes Ember and Ember-Data with a requirement for a lazy-loaded tree-list. Within the API, there is an endpoint called /roots which contains children such as /roots/categories and /roots/components. These children are not fully lo ...

Display user information from another component using Vue's dynamic routing feature

In my UserList.vue component, I have a list of users that I want to display on individual user profiles in the SingleUser.vue component. What is the easiest way to achieve this? The user details are stored in the UserList.vue component. When a specific us ...

Solving the problem of 'json mime-type on 2003 server

I am currently facing an issue: On a 2003 server with iis 6, I have a functioning solution. However, during every deployment of the solution, I find myself having to manually configure the MIME type on the iis. Although I have implemented this in my web ...

How can I utilize a custom function to modify CSS properties in styled-components?

I am working with styled components and need to set the transform property based on certain conditions: If condition 1 is true, set the value to x. If condition 2 is true, set the value to y. If neither condition is true, set the value to null. Despite ...

guide on launching react with pure javascript

Is it feasible to operate react "straight out of the box" using only JavaScript? In essence, I am seeking a way to utilize react by simply utilizing notepad to create the page (without needing to install and configure node etc.). More specifically - 1) ...

Iterating through object using jQuery

I'm facing an issue with iterating through a JSON object for the first time. The JSON is structured like this: { "response": { "2012-01-01": { "Available": 99, "Variations": [ { ...

What is the best way to transform Json into a Map in Dart/Flutter?

I have a json dataset and I'm looking to convert it into a Map in dart/flutter. Here is the json data: {"kabupaten": [ { "jec_kabupaten_id": "71", "jec_propinsi_id": "8" ...

What occurs if we trigger an emit event on a socket that is already disconnected?

If the socket is already disconnected, what are the potential consequences of executing the code below? socket.emit("event", event_data); ...

Incorporate different courses tailored to the specific job role

https://i.stack.imgur.com/iGwxB.jpg I am interested in dynamically applying different classes to elements based on their position within a list. To elaborate: I have a list containing six elements, and the third element in this list is assigned the class ...

Dividing an array of characters within an ng-repeat and assigning each character to its individual input tag

Hello, I'm currently learning Angular and I have a unique challenge. I want to take the names in a table and break each name into individual <input> tags, so that when a user clicks on a letter, only that letter is selected in the input tag. For ...

What is the best way to initiate JavaScript using a button click in WordPress?

I need to add a button to a WordPress page that triggers a JavaScript function when clicked. Here is the HTML code: <!DOCTYPE html> <html lang="en"> <head> <title></title> </head> <body> < ...

Creating a React component dynamically and applying unique custom properties

I'm currently in the process of refactoring my React code to enhance its usability in situations where direct use of Babel is not possible, such as in short snippets of JavaScript embedded on web pages. As part of this refactor, I am setting up a conc ...

Converting JSON to Array in Laravel using Casting

Can you figure out why the eloquent $casts feature isn't functioning properly? I've set up a JSON column type and used the following code to cast it as an array: protected $casts = [ 'fields' => 'array' ]; However, w ...

Alignment of content layout across two wrapper elements

My goal is to achieve a specific layout where each pair of cards in a two-column layout is aligned based on the card with the largest content. Both cards share the same content layout and CSS. If you have any ideas or implementations that could help me ac ...

Selenium fails to compare two values due to a ComparisonFailure

This block of code retrieves product prices and performs some actions on a website: List<WebElement> ProductPrices1 = driver.findElements(By.className("prc-slg")); String text1Price = ProductPrices1.get(0).getText(); thread ...

Jquery Ajax failing to retrieve a response

Here's the jQuery script I am using to fetch data from my server: $(".login_button").click(function () { var username = $(".username").val(); var userkey = $(".userkey").val(); $.ajax({ type: "GET", url: "http://192.168.0. ...

How can I include the paths for "testng.xml" and log4j2.xml in my pom.xml file for a Selenium - Maven/TestNG project, ensuring the executable .jar file can run on any machine?

I am currently utilizing Maven, TestNG, and Log4j2 in my project. Our goal is to generate an executable .jar file that will execute testng.xml via the pom.xml file. As of now, I have successfully created an executable .jar file and ran it without any iss ...

What is the most efficient and hygienic method for storing text content in JavaScript/DOM?

Typically, I encounter version 1 in most cases. However, some of the open source projects I am involved with utilize version 2, and I have also utilized version 3 previously. Does anyone have a more sophisticated solution that is possibly more scalable? V ...

Interactive Vue components with dynamic children and sub-children

In my Vue application, I have a component called Address.vue which contains a child component called Contact.vue. One address can contain multiple components What I have accomplished: I have implemented the functionality in the Address.vue component t ...

Employing multer in conjunction with superagent to enable file uploads from a React application

I am new to using multer and experiencing some difficulties with it. My goal is to upload an image file from a react client using the superagent library to my server. However, the req.file data always shows as undefined in my code: On the server side : ...