I want to add JSON message on REST controller class(methods). For example i have delete method look's like:
#DeleteMapping("/people/{id}")
public ResponseEntity<PersonDto> deletePerson(#PathVariable Long id) {
return personService
.deletePerson(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
I want to return message Person (maybe numer of id) deleted.
Should i use ExceptionHandler? Or Can i do this Using exceptionHnadler?
Define a ResponseBean POJO class as
public class ResponseBean {
public final Long id;
public final String msg;
public ResponseBean(Long id, String msg) {
this.id = id;
this.msg = msg;
}
public Long getId() {
return id;
}
public String getMsg() {
return msg;
}
}
Change your controller method as
#DeleteMapping("/people/{id}")
public ResponseEntity<ResponseBean> deletePerson(#PathVariable Long id) {
return personService
.deletePerson(id)
.map(dto -> new ResponseBean(dto.getId(), "Person Deleted Successfully"))
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
Response
{
"id" : 2,
"msg" : "Person Deleted Successfully"
}
You can customize ResponseBean class as per your need.
Related
This is probably some basic question. I am using JAX-RS (jersey implementation) and my code is as follows.
#Path("/data")
#GET
#Produces(MediaType.APPLICATION_JSON)
public Car handlerFn(#Context HttpServletResponse res)
{
res.setStatus(HttpServletResponse.SC_OK);
Car carObject = new Car(42,"Maruthi", "Alto");
return carObject;
}
Car Entity is as follows
public class Car {
int id;
String name;
String model;
public Car() {
}
public Car(int id, String name, String model)
{
this.id=id;
this.name = name;
this.model = model;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getModel() {
return model;
}
}
The output I am getting is in one line as follows
{"id":42,"model":"Alto","name":"Maruthi"}
In place of this I want the each member in different lines as follows
{
"id": 42,
"model": "Alto",
"name": "Maruthi"
}
How can I do that?
I am new to springboot, i am getting a response as below in my json response:
"Number": "08002050"
I have defined it as String in my spring boot app.
I want to get a response as below:
"Number": 08002050
How do i accomplish this. please help
You can manage it in server side with a tricky way.
public class User {
private int id;
private String name;
#JsonIgnore // ignore this field when serialize
private String number;
#JsonProperty(value = "number") // change name of field when serialize
private int intValueOfNumber;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public int getIntValueOfNumber() {
return Integer.parseInt(number); // parse number string to int
}
public void setIntValueOfNumber(int intValueOfNumber) {
this.intValueOfNumber = intValueOfNumber;
}
}
In this entity #JsonIgnore annotation is ignore your field for JSON serialization and pass intValueOfNumber as int to JSON. Your json will be following:
{"id":1,"name":"Java","number":44124}
You may lost zero suffix of number string when you parse it to int.
Below I have given my POJO structure and the current out put and expected output. My requirement is, when I am printing the JSON format the variable called "applicationUsage " automatically included in my output JSON as key, But I dont want to add "applicationUsage " key in my json format and only wants to show the values stored in this field. Can anyone help me with the code.
#JsonRootName(value = "MediationUserCacheRequest")
#JsonTypeInfo(include = As.WRAPPER_OBJECT, use = Id.NAME)
#JsonTypeName(value = "MediationUserCacheRequest")
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({ "eventName", "eventType", "action" })
public class MedationUsageReport implements Serializable {
private final static long serialVersionUID = -2077028266055844229L;
#JsonProperty("eventName")
private String eventName;
#JsonProperty("eventType")
private String eventType;
#JsonProperty("action")
private String action;
private Map<String, List<MediationApplicationUsageResport>> applicationUsage = null;
#JsonProperty("eventName")
public String getEventName() {
return eventName;
}
#JsonProperty("eventName")
public void setEventName(String eventName) {
this.eventName = eventName;
}
#JsonProperty("eventType")
public String getEventType() {
return eventType;
}
#JsonProperty("eventType")
public void setEventType(String eventType) {
this.eventType = eventType;
}
#JsonProperty("action")
public String getAction() {
return action;
}
#JsonProperty("action")
public void setAction(String action) {
this.action = action;
}
public Map<String, List<MediationApplicationUsageResport>> getApplicationUsage() {
return applicationUsage;
}
public void setApplicationUsage(Map<String, List<MediationApplicationUsageResport>> applicationUsage) {
this.applicationUsage = applicationUsage;
}
}
Output:
{"MediationUserCacheRequest":{"eventName":"STORAGE","eventType":"CURRENT_USAGE","action":"usagereport","applicationUsage":{"nuxeo":[ ...
Wanted:
{"MediationUserCacheRequest":{"eventName":"STORAGE","eventType":"CURRENT_USAGE","action":"usagereport",{"nuxeo":[ ...
Simply mark it with #JsonAnyGetter annotation.
#JsonAnyGetter
public Map<String, List<MediationApplicationUsageResport>> getApplicationUsage() {
return applicationUsage;
}
Try annotating the getApplicationUsage() getter with #JsonUnwrapped
Java class (used as a Data Transfer Object):
class Resource also has a field named id with a different type along with its getter and setter, hence the syntax error.
class A extends Resource
{
private int id;
public int getId() { return id; } // syntax error as getId() function already exists in Resource
public void setId(int id) { this.id = id; }
}
Since the above class is a DTO, a JSON response (with field id) will be mapped to it, and getId() cannot be used, I want to change the field to _id_ and change getter and setter correspondingly, and mark it with an annotation saying bind this to id field.
Note: I'm using spring boot. I tried using #JsonProperty annotation but that didn't work. Is there an annotation for doing this in spring?
Googled and found this question: Jackson serialization: how to ignore superclass properties. Adapted it for your problem.
public class A extends B {
private int id;
public A(int id) {
super.setId("id" + id);
this.id = id;
}
#Override
#JsonProperty("_id_")
public String getId() {
return super.getId();
}
#Override
#JsonProperty("_id_")
public void setId(String id) {
super.setId(id);
}
#JsonProperty("id")
public int getIntId() {
return id;
}
#JsonProperty("id")
public void setIntId(int id) {
this.id = id;
}
}
public class B {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Tested it with this:
#RestController
public class TestController {
#GetMapping("/test")
public A test() {
return new A(1);
}
}
And the output was:
{
"_id_": "id1",
"id": 1
}
public A extends Resource {
private int id;
#JsonProperty("_id")
public int getId() {
return id;
}
#JsonProperty("id")
public void setId(int id) {
this.id = id;
}
}
the method names should be different, so jackson parses it as different fields, not as one field.
I have a problem with converting my lists to JSON. I'd like to use generic lists with templating.
This doesn't work for me. My POJO:
class Event {
private Long id;
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
}
Generic list result:
public class ListResponse<T> {
private List<T> result = new ArrayList<T>();
public List<T> getResult() {
return result;
}
public void setResult(List<T> result) {
this.result = result;
}
}
Concrete list result:
public class EventListResponse extends ListResponse<Event> {}
In my resource class I'm using this:
#PermitAll
#Path("/list")
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public EventListResponse getEvents() {
//...
EventListResponse response = new EventListResponse();
List<Event> events = eventService.getList();
response.setResult(events);
return response;
}
The serialize doesnt work in this case, I end up with Strings insead of "Event" JSON objects.
I get results like:
array(3) { ["type"]=> string(17) "eventListResponse" ["result"]=> array(1) { [0]=> string(38) "com.mypackage.model.Event#3a622482" } }
Whats the problem here?
Thank you