I got a school assignment asking me to change the content of JSON Response
from
{"name" : "Bob"}
to
{"greeting" : "Hello, Bob"}
this is my ResponseDTO
public class HelloWorldResponseDTO {
private String name;
}
and this is my Entity
public class HelloWorld {
private String name;
public HelloWorldResponseDTO convertToResponse() {
return new HelloWorldResponseDTO(this.name);
}
}
Related
I am calling an endpoint that returns back a JSON response.
Here is sample of the JSON response:
{
"main": {
"test":{
"Date": "2022-06-06",
"Id": 1234
},
"response" :[
{
"responseTime": 100,
"redirects": 0
}
]
}
}
Here is my code to get the JSON response:
HttpEntity<String> request = new HttpEntity<>(setHeaders());
ResponseEntity<Main> response = restTemplate.exchange(endpoint, HttpMethod.GET, request, Main.class);
I want to convert the response to an entity object, with the response section being a HashMap. I tried the following but I get an error that the conversion failed
public class Main {
private Test test;
private Response response;
}
public class Test{
private Date Date;
private int Id;
}
public class Response{
private Map<String, String> responseMap;
}
Can someone help me understand what I am doing wrong?
what you are getting back is an Object containing a main object
{
"main": {
"test":{
"Date": "2022-06-06",
"Id": 1234
},
"response" :[
{
"responseTime": 100,
"redirects": 0
}
]
}
}
which means
// Can be named whatever
public class Response {
private Main main;
//constructor, getter setters
}
public class Main {
private Test test;
private ArrayList<Data> response;
//constructor, getter setters
}
public class Test {
private LocalDate date;
private int id;
//constructor, getter setters
}
public class Data {
private int responseTime;
private int redirects;
//constructor, getter setters
}
And then you call and plase the response data in the top level object
ResponseEntity<Main> response = restTemplate.exchange(endpoint, HttpMethod.GET, request, Response.class);
I have created a RESTful webservice using Spring boot to add a record to H2 database but when I send data from postman to my handler method I get null values on the server side and on the response sent to the client side as well, could anybody help me?
Eclipse Snapshot
Postman Snapshot
My Controller Code:
#RestController
public class AlienController {
#Autowired
AlienRepo repo;
#RequestMapping("/")
public String home() {
return"home.jsp";
}
#PostMapping(path="/alien")
public Alien addAlien(Alien alien) {
System.out.println(alien);
repo.save(alien);
return alien;
}
My DAO Class:
#Entity
public class Alien {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int aid;
private String aname;
private String lang;
public int getAid() {
return aid;
}
public void setAid(int aid) {
this.aid=aid;
}
public String getAname() {
return aname;
}
public void setAname(String aname) {
this.aname=aname;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang=lang;
}
#Override
public String toString() {
return "Alien Info: Aid=" + aid + ", Aname=" + aname + ", Lang=" +lang;
}
}
My AlienRepository code:
public interface AlienRepo extends JpaRepository<Alien, Integer>{
}
You should use the annotation #RequestBody
public Alien addAlien(#RequestBody Alien alien)
You should inform Spring that you are waiting for a HttpRequest that contains a Body , Spring will automatically deserialize the inbound HttpRequest body onto Java object
I have a json context like below:
{
"data": {
"details": {
"en-CA": {
"languageCode": "en-CA",
"isPrimaryLocale": false
},
"en-US": {
"languageCode": "en-US",
"isPrimaryLocale": true,
"languageDisplayName": "English (United States)",
}
}
}
}
To map it with GSON in java:
I created this classes:
public class ApiResponseSingleDto
{
private ResponseDetail data;
}
public class ResponseDetail
{
private ResponseDetails details;
#Getter
public static class ResponseDetails
{
public HashMap<String, LocaleDetail> row = new HashMap<>();
}
}
public class LocaleDetail
{
private String languageCode;
private Boolean isPrimaryLocale;
private String languageDisplayName;
}
When I try to map json to Java POJO class, HashMap doesn't work. Is there any suggestion?
To map it:
GSON.fromJson("...json", Type type...);
Just try to replace:
public class ApiResponseSingleDto
{
private ResponseDetail data;
}
public class ResponseDetail
{
private Map<String, LocaleDetail> details;
}
public class LocaleDetail
{
private String languageCode;
private Boolean isPrimaryLocale;
private String languageDisplayName;
}
Also json seems to be incorrect: "languageDisplayName": "English (United States)",
should be just "languageDisplayName": "English (United States)"
One more note: I believe you should have public fields or at least getters for them
I have been trying unsuccessfully now to parse this message. Using the AWS Simple Queue Service API, I follow instructions and do the following...
for(Message m : Messages){
System.out.println(m.getBody());
}
This returns a JSON string in this structure:
{
"Records": [
{
"EventSource": "",
"EventVersion": "",
"EventSubscriptionArn": "",
"Sns": {
"Type": "",
"MessageId": "",
"TopicArn": "",
"Subject": null,
"Message": ""
"Timestamp": "",
"SignatureVersion": "",
"Signature": "”
"SigningCertUrl": "",
"UnsubscribeUrl": "",
"MessageAttributes": {}
}
}
]
}
I have been trying to parse this entire thing to a Java Object using GSON so that I can extract the "Message" parameter (which also contains JSON) and then use GSON to parse that (done and works when I just pass that text directly).
These are the classes I set up, but this will not work -- Each one has public getters and setters.....
Records Class:
public class Records {
public ArrayList<ExceptionMessages> exceptionMessages = new ArrayList<ExceptionMessages>();
public ArrayList<ExceptionMessages> getExceptionMessages() {
return exceptionMessages;
}
public void setExceptionMessages(ArrayList<ExceptionMessages> exceptionMessages) {
this.exceptionMessages = exceptionMessages;
}
Message Class:
public class ExceptionMessages {
public String EventSource;
public String EventVersion;
public String EventSubscriptionArn;
public Sns messageJSON;
}
Sns Class (where the message is stored):
public class Sns {
public String Type;
public String MessageId;
public String TopicArn;
public String Subject;
public String Message;
public String Timestamp;
public String SignatureVersion;
public String Signature;
public String SigningCertUrl;
public String UnsubscribeUrl;
public String MessageAttributes;
}
I get a null pointer exception when trying to .get(0) of the ArrayList so it's empty and parsing did not take place.
Here is how I'm calling it...
I'm sending m.getBody() to a parsing method and attempting to parse like this:
Gson gson = new Gson();
Records record = new Records();
gson.fromJson(JSONString.replaceAll("\\s+", ""), Records.class);
The structure should be
class RecordContainer {
ArrayList<Record> Records;
}
class Record {
public String EventSource;
public String EventVersion;
public String EventSubscriptionArn;
public Sns Sns;
}
class Sns {
public String Type;
public String MessageId;
public String TopicArn;
public String Subject;
public String Message;
public String Timestamp;
public String SignatureVersion;
public String Signature;
public String SigningCertUrl;
public String UnsubscribeUrl;
public MessageAttributes MessageAttributes;
}
I built a REST API Service using Java Spring Cloud / Boot. Firstly, I made a simple class connected to a MongoDB and a controller with service that should allow me to add, delete, update and get all the objects. When using POSTMAN these all work, however when I want to add or update an object using redux and fetch API I get a status 400 and "bad request" error. This seems to have something to do with the JSON I'm sending in the body but it is the exact same format of JSON that is working with for example POSTMAN.
My action in Redux. For simplicity / test purposes I added an object at the top in stead of using the object being sent from the page.
var assetObject = {
"vendor" : "why dis no work?",
"name": "wtf",
"version": "231",
"category" : "qsd",
"technology" : "whatever"
}
export function addAsset(access_token, asset) {
return dispatch => {
fetch(constants.SERVER_ADDRESS + '/as/asset/add',
{
method: 'POST',
credentials: 'include',
headers: {
'Authorization': 'Bearer' + access_token,
'Content-Type': 'application/json'
},
body: assetObject
})
.then(res => dispatch({
type: constants.ADD_ASSET,
asset
}))
}
}
Controller code in Java Spring:
#RequestMapping(method = RequestMethod.POST, path = "/add")
public void addAsset(#RequestBody Asset asset) {
assetService.addAsset(asset);
}
Status ok while doing it in postman:
The error I get when using Redux / Fetch API (I only removed the directory structure because it has company name in it):
Have been stuck on this for a while, any help is much appreciated!
EDIT Asset Object:
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "assets")
public class Asset {
#Id
private String id;
private String vendor;
private String name;
private String version;
private String category;
private String technology;
public Asset() {
}
public Asset(String id,
String vendor,
String name,
String version,
String category,
String technology) {
this.id = id;
this.vendor = vendor;
this.name = name;
this.version = version;
this.category = category;
this.technology = technology;
}
public String getId() {
return id;
}
public String getVendor() {
return vendor;
}
public String getName() {
return name;
}
public String getVersion() {
return version;
}
public String getCategory() {
return category;
}
public String getTechnology() {
return technology;
}
public void setId(String id) {
this.id = id;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public void setName(String name) {
this.name = name;
}
public void setVersion(String version) {
this.version = version;
}
public void setCategory(String category) {
this.category = category;
}
public void setTechnology(String technology) {
this.technology = technology;
}
}
your error message says :
; required request body is missing
i think the error happens when your controller method
trying to form an object from the incoming request.
when you are sending the request you have to set each and every field related to the object.
if you are planning on not setting a property you should mark that field with #JsonIgnore annotation.
you can use #JsonIgnore annotation on the variable which will ignore this property
when forming the object as well as when outputing the object.
use #JsonIgnore annotation on the setter method , which i think you should do now since
you are ignoring the id property when making the request.
#JsonIgnore
public void setId(String id) {
this.id = id;
}
and you can return httpstatus code from the controller method,
so that client knows request was successful
#ResponseBody
public ResponseEntity<String> addAsset(#RequestBody Asset asset) {
return new ResponseEntity<String>("your response here", HttpStatus.OK);
}