Answer the question
In order to leave comments, you need to log in
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}`);
}
});
});
Answer the question
In order to leave comments, you need to log in
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\" } }";
}
data: { command: "GetDriverInfo" },
and most importantly, why and how it should be processed by the controller. 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 questionAsk a Question
731 491 924 answers to any question