T
T
thatmaniscool2022-02-23 11:09:22
Java
thatmaniscool, 2022-02-23 11:09:22

Spring how to send JSON string?

I am writing a class in spring.

import java.util.HashMap;
import java.util.Map;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class JSON {

  @GetMapping("/json")
  public String getJSON2() {
    return "{ \"id\": 10, \"name\": \"Clementina DuBuque\", \"username\": \"Moriah.Stanton\","
        + " \"email\": \"[email protected]\", "
        + "\"address\": { \"street\": \"Kattie Turnpike\", "
        + "\"suite\": \"Suite 198\", \"city\": \"Lebsackbury\", "
        + "\"zipcode\": \"31428-2261\", \"geo\": { \"lat\": "
        + "\"-38.2386\", \"lng\": \"57.2232\" } }";
  }
}


$(document).ready (function(){
    $.ajax({
        url: "/api/json", //https://localhost:8080 - как я понял, вообще использовать нельзя. 
        method: "GET",
        data: { command: "GetDriverInfo" }, 
        dataType: "json",
        success(response) {
            console.log(response.driverVer);
        },
        error(xhr) {
            console.log(`${xhr.status}: ${xhr.statusText}`);
        }
    });
});


As a result of execution, the function is not executed, but if you type https://localhost:8080/api/json in the browser, the string is displayed.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2022-02-23
@thatmaniscool

Good afternoon.
Did you copy the js code from somewhere?
1) The very idea of ​​returning json from the controller in this form is not very good. You need to return dto. And jackson already serializes to json

@GetMapping("/json")
  public String getJSON2() {
    return "{ \"id\": 10, \"name\": \"Clementina DuBuque\", \"username\": \"Moriah.Stanton\","
        + " \"email\": \"[email protected]\", "
        + "\"address\": { \"street\": \"Kattie Turnpike\", "
        + "\"suite\": \"Suite 198\", \"city\": \"Lebsackbury\", "
        + "\"zipcode\": \"31428-2261\", \"geo\": { \"lat\": "
        + "\"-38.2386\", \"lng\": \"57.2232\" } }";
  }

2) As your colleague Dmitry Roo noted , what happens in the browser and what happens in the js code are two different things.
Here, look:
In the code below, you are making a GET request to /api/json.
Firstly, it is not clear what it is: data: { command: "GetDriverInfo" },and most importantly, why and how it should be processed by the controller.
Secondly, it is not clear what parameter you want to get:
console.log(response.driverVer);if you do not have such a driveVer parameter in json.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question