How to get rest response that contains only certain object's json? - json

My goal is to get rest services working on spring boot web application.
But I am struggling with finding out how to tell response to include object's json only.
To be more precise, when calling http://localhost:8080/api/db/Keyboard/2, I intend to receive object with id 2 in json format and only:
{
"id": 2,
"language": "en"
}
But instead I get:
{
"status": 200,
"entity": {
"id": 2,
"language": "en"
},
"metadata": {},
"length": -1,
"allowedMethods": [],
"cookies": {},
"headers": {},
"actualEntity": {
"id": 2,
"language": "en"
},
"links": [],
"statusInfo": {
"reasonPhrase": "OK",
"statusCode": 200,
"family": "SUCCESSFUL"
},
"stringHeaders": {}
}
Clearly response contains too much info. Only the entity part is needed. How to reach intended result / adjust conditionally the response?
Below some files that might be relevant.
TestController.java:
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import main.domain.DaoApi;
import main.domain.Keyboard;
#RestController
public class TestController<T, K> {
private final static Map<String, Class<?>> tableClassMap = new HashMap<>();
#Autowired
private DaoApi<T, K> daoApi;
static {
addEntryTableClassMap(Keyboard.class);
}
#RequestMapping(value = "/api/db/{tableName}/{id}", method = RequestMethod.GET)
public Response getById(#PathVariable(value = "tableName") String tableName, #PathVariable(value = "id") Integer id) {
ResponseBuilder responseBuilder;
T entity = (T) daoApi.findById((Class<T>) getClassFromTableClassMap(tableName), id);
if (entity != null) {
responseBuilder = Response.ok(entity);
} else {
responseBuilder = Response.status(Status.NOT_FOUND);
}
return responseBuilder.build();
}
private static <C> void addEntryTableClassMap(Class<C> clazz) {
tableClassMap.put(clazz.getSimpleName().toLowerCase(), clazz);
}
private static <C> Class<C> getClassFromTableClassMap(String tableName) {
return (Class<C>) tableClassMap.get(tableName.toLowerCase());
}
}
Keyboard.java:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.transaction.annotation.Transactional;
#Transactional
#Entity
#Table(name = "keyboard")
public class Keyboard {
#Id
#Column(updatable = false)
private int id;
private String language;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
}
DaoApi.java:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component
public class DaoApi<T, K> {
#Autowired
SessionFactory sessionFactory;
public T findById(Class<T> clazz, Integer id) {
Session session = sessionFactory.openSession();
T t = (T) session.get(clazz, id);
session.close();
return t;
}
}

Received comment that helped me to solution:
#RequestMapping(value = "/api/db/{tableName}/{id}", method = RequestMethod.GET)
public T getById(#PathVariable(value = "tableName") String tableName, #PathVariable(value = "id") Integer id) {
ResponseBuilder responseBuilder;
T entity = (T) daoApi.findById((Class<T>) getClassFromTableClassMap(tableName), id);
if (entity != null) {
responseBuilder = Response.ok(entity);
return (T) responseBuilder.build().getEntity();
} else {
responseBuilder = Response.status(Status.NOT_FOUND);
//some additional code here
return (T) responseBuilder.build();
}
}

Related

JSON parse error: Cannot deserialize value

I want to insert multiple data in postman but, I get this eror
"message": "JSON parse error: Cannot deserialize value of type com.test.rest.api.dtos.AnggotaDTO from Array value (token JsonToken.START_ARRAY); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type com.test.rest.api.dtos.AnggotaDTO from Array value (token JsonToken.START_ARRAY)\n at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 1]",
How i can resolve this eror ?
This is my request body, post in postman
[
{
anggotaNama: "AAA",
anggotaUsia: 16
},
{
anggotaNama: "BBB",
anggotaUsia: 17
},
{
anggotaNama: "CCC",
anggotaUsia: 18
}
]
This is my dtos.AnggotaDTO
package com.test.rest.api.dtos;
import lombok.Data;
import lombok.NoArgsConstructor;
#Data
#NoArgsConstructor
public class AnggotaDTO {
private long anggotaId;
private String anggotaNama;
private int anggotaUsia;
}
This my controller
package com.test.rest.api.controllers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.test.rest.api.dtos.AnggotaDTO;
import com.test.rest.api.models.Anggota;
import com.test.rest.api.repositories.AnggotaRepository;
#RestController
#RequestMapping("/api")
public class AnggotaController {
#Autowired
private AnggotaRepository anggotaRepository;
ModelMapper modelMapper = new ModelMapper();
private Anggota convertAnggotaToEntity (AnggotaDTO anggotaDto) {
return modelMapper.map(anggotaDto, Anggota.class);
}
private AnggotaDTO convertAnggotaToDTO (Anggota anggota) {
return modelMapper.map(anggota, AnggotaDTO.class);
}
// API CREATE Anggota
#PostMapping("/anggota/create")
public Map<String, Object> createAnggota(#RequestBody AnggotaDTO anggotaDTO) {
Map<String, Object> mapResult = new HashMap<>();
Anggota anggota = convertAnggotaToEntity(anggotaDTO);
anggota.setAnggotaNama(anggotaDTO.getAnggotaNama());
anggota.setAnggotaUsia(anggotaDTO.getAnggotaUsia());
mapResult.put("message", "Craete Success");
mapResult.put("data", anggotaRepository.save(anggota));
return mapResult;
}
// API READ Anggota
#GetMapping("/anggota/get/findall")
public Map<String, Object> getAllAnggota () {
Map<String, Object> mapResult = new HashMap<>();
List<AnggotaDTO> listAnggotaDto = new ArrayList<>();
for (Anggota anggota : anggotaRepository.findAll()) {
AnggotaDTO anggotaDto = convertAnggotaToDTO(anggota);
listAnggotaDto.add(anggotaDto);
}
String message;
if (listAnggotaDto.isEmpty()) {
message = "Data is empty";
}
else {
message = "Show all data";
}
mapResult.put("message" , message);
mapResult.put("data", listAnggotaDto);
mapResult.put("total", listAnggotaDto.size());
return mapResult;
}
// API UPDATE Anggota
#PutMapping("/anggota/update")
public Map<String, Object> updateAnggota (#RequestParam(value="anggotaId") long anggotaId, #RequestBody AnggotaDTO anggotaDto) {
Map<String, Object> mapResult = new HashMap<>();
Anggota anggota = anggotaRepository.findById(anggotaId).orElse(null);
anggota.setAnggotaNama(anggotaDto.getAnggotaNama());
anggota.setAnggotaUsia(anggotaDto.getAnggotaUsia());
mapResult.put("message", "Update success");
mapResult.put("data", anggotaRepository.save(anggota));
return mapResult;
}
// API Delete Employee
#DeleteMapping("/anggota/delete/{anggotaId}")
public Map<String, Object> deleteAnggota (#PathVariable(value="anggotaId") long anggotaId) {
Map<String, Object> mapResult = new HashMap<>();
Anggota anggota = anggotaRepository.findById(anggotaId).orElse(null);
anggotaRepository.delete(anggota);
mapResult.put("message", "Delete Success");
return mapResult;
}
}

Spring Boot: how can I parse a JSON which consists of an array of objects and use a path variable to get a specific value?

I've got the following task:
I need to Produce a Spring Boot REST API that reads in data from a JSON file and allows the user to filter by colour.
The URL should look similar to: http://localhost:8080/cars?colour=red
The input data is in the included JSON file (cars.json)
It is of the form:
{
"cars": [
{
"brand": "ford",
"model": "fiesta",
"fuel": "petrol",
"doors": 5,
"colour": "blue"
}
]
}
I'm struggling to structurize JSON parsing classes properly, and here's my code
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.challenge.esure.domain.Cars;
import com.challenge.esure.exceptions.ColourNotFoundException;
import com.challenge.esure.service.MainService;
#RestController
public class MainController {
private final MainService mainService;
#Autowired
public MainController(MainService mainService) {
this.mainService = mainService;
}
#GetMapping("/all")
public List<Cars> getAll() throws IOException {
return mainService.getAllRecords();
}
#GetMapping("/cars?colour={colour}")
public Cars getColour(#PathVariable("colour") String colour) throws IOException, ColourNotFoundException {
return mainService.getCarColour(colour);
}
}
//Service:
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import com.challenge.esure.domain.CarDetails;
import com.challenge.esure.domain.Cars;
import com.challenge.esure.exceptions.ColourNotFoundException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
#Service
public class MainService {
public List<Cars> getData() throws IOException{
Resource resource = new ClassPathResource("cars.json");
InputStream input = resource.getInputStream();
File file = resource.getFile();
ObjectMapper objectMapper = new ObjectMapper();
List<Cars> car = Arrays.asList(objectMapper.readValue(file, Cars[].class));
return car.stream().collect(Collectors.toList());
}
public List<Cars> getAllRecords() throws IOException {
return getData();
}
public Cars getCarColour(String colour) throws ColourNotFoundException, IOException {
return getData().stream()
.filter(Cars -> Cars.getColour().equals(colour))
.findAny()
.orElseThrow(() -> new ColourNotFoundException("We don't have cars with that colour"));
}
}
// Domain
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class Cars {
private ArrayList<Object> cars;
private String brand;
private String model;
private String fuel;
private Integer doors;
private String colour;
public Cars() {
}
public Cars(ArrayList<Object> cars, String brand, String model, String fuel, Integer doors, String colour) {
this.cars = cars;
this.brand = brand;
this.model = model;
this.fuel = fuel;
this.doors = doors;
this.colour = colour;
}
public ArrayList<Object> getCars() {
return cars;
}
public void setCars(ArrayList<Object> cars) {
this.cars = cars;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getFuel() {
return fuel;
}
public void setFuel(String fuel) {
this.fuel = fuel;
}
public Integer getDoors() {
return doors;
}
public void setDoors(Integer doors) {
this.doors = doors;
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
}
//Exception
public class ColourNotFoundException extends Exception {
public ColourNotFoundException(String what) {
super(what);
}
}
You can use the below data structure
#JsonIgnoreProperties(ignoreUnknown = true)
public class CarResponse {
List<Car> cars;
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
#Override
public String toString() {
return "CarResponse{" +
"cars=" + cars +
'}';
}
}
public class Car {
private String brand;
private String model;
private String fuel;
private Integer doors;
private String colour;
}
CarResponse carResponse= objectMapper.readValue(jsonString, CarResponse.class);

Using List for JSON Array

Updating based on further exploring and thanks to #pinaka30 for the comment-
I wanted to verify if I deserialize JSON array into List, will that preserve the sequence.
I took the below JSON
{
"MyJSON": {
"name": "Any Name",
"values": [
"1111",
"2222",
"3333",
"4444",
"5555",
"6666"
]
}
}
The DTO that I created is as follows:
package com.jsonrelated.jsonrelated;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"MyJSONMapping"
})
public class MyJSONMapping {
#JsonProperty("MyJSON")
#Valid
#NotNull
private MyJSON myJSON;
#JsonProperty("MyJSON")
public MyJSON getMyJSON() {
return myJSON;
}
#JsonProperty("MyJSON")
public void setMyJSON(MyJSON myJSON) {
this.myJSON = myJSON;
}
}
package com.jsonrelated.jsonrelated;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import java.util.List;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"name",
"values"
})
public class MyJSON {
#JsonProperty("name")
String name;
#JsonProperty("values")
List<String> values;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getValues() {
return values;
}
public void setValues(List<String> values) {
this.values = values;
}
}
Then I have created a REST API and sending that JSON as request Body
#RequestMapping(path="generateMyJSONChart",method=RequestMethod.POST,produces="application/json",consumes="application/json")
public String generateMyJSONChart(#Valid #RequestBody MyJSONMapping myJSONMapping, #RequestParam("type") #NotBlank String type) throws IOException {
List comparedProducts = myJSONMapping.getMyJSON().getValues();
Iterator i = comparedProducts.iterator();
while (i.hasNext())
{
String name = (String) i.next();
System.out.println(name);
}
return "nothing";
}
I was checking if the sequence of the values in "Values" as in
"values": [
"1111",
"2222",
"3333",
"4444",
"5555",
"6666"
]
are preserved if we deserialize them into List as in
#JsonProperty("values")
List<String> values;
I have run it multiple times with 100 elements in the values and I see the order is preserved.
Adding a good post already there Is the order of elements in a JSON list preserved? so mine seems to be duplicate.

Data mismatch between Json response and database

I'm retrieving data from mysql using spring boot, hibernate and producing the response as REST service. But while checking in Postman the data mismatches. Here is my code.
Controller Class:
#RestController
public class NotificationController<T> extends RestUtils<T> {
#Autowired
NotificationService<T> service;
#RequestMapping(value = "/notification/getNotifications", method = RequestMethod.POST, headers = "Accept=application/json")
public #ResponseBody Object getNotifications(#RequestBody NotificationBean notificationBean) {
try {
return getSuccessResponse(service.getNotifications(notificationBean), "Total Count: ",
service.getNotificationsCount(notificationBean));
} catch (StudawnException e) {
return getErrorResponse(e.getMessage());
}
}
}
Service Implementation:
#Service
public class NotificationServiceImpl<T> implements NotificationService<T> {
#Autowired
NotificationRepository notificationRepository;
#SuppressWarnings("deprecation")
#Transactional
#Override
public Object getNotifications(NotificationBean notificationBean) throws StudawnException {
Sort sort = new Sort(new Sort.Order(Direction.DESC, "dateCreated"));
Pageable pageable = new PageRequest(notificationBean.getPage(), notificationBean.getSize(), sort);
return notificationRepository.findNotificationsByStudentId(notificationBean.getStudentId(), pageable);
}
}
Repository:
#Repository
public interface NotificationRepository<T> extends JpaRepository<Notification, Integer> {
#Query(NotificationQuery.findNotificationsByStudentId)
List<Notification> findNotificationsByStudentId(#Param("studentId") Integer studentId, Pageable pageable);
#Query(NotificationQuery.findNotificationsCountByStudentId)
Integer findNotificationsCountByStudentId(#Param("studentId")Integer studentId);
}
Query class:
public class NotificationQuery {
public static final String findNotificationsByStudentId = "select n from #{#entityName} n where n.student.studentId = :studentId and n.isActive=true";
public static final String findNotificationsCountByStudentId = "select count(n) from #{#entityName} n where n.student.studentId=:studentId and n.isActive=true";
}
Model class
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#Entity
#Table(name = "notification")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = { "dateCreated" }, allowGetters = true)
public class Notification {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "notification_id")
private int notificationId;
#ManyToOne
#JoinColumn(name = "student_id")
private Student student;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created_date", nullable = false, updatable = false)
#CreatedDate
private Date dateCreated;
#Column(name = "is_active")
private boolean isActive;
#Column(name = "has_read")
private boolean hasRead;
#Column(name = "message", length = 150)
private String message;
public int getNotificationId() {
return notificationId;
}
public void setNotificationId(int notificationId) {
this.notificationId = notificationId;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean isActive) {
this.isActive = isActive;
}
public boolean isHasRead() {
return hasRead;
}
public void setHasRead(boolean hasRead) {
this.hasRead = hasRead;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Json Request
{
"studentId":101,
"page":0,
"size":10
}
Json Response
The date in 'dateCreated' field mismatch with database. The actual date in DB is '2018-03-06' but in response it is '2018-03-05'
{
"response": [
{
"notificationId": 4,
"student": {
"studentId": 101,
"studawnId": "1234",
"firstName": "arun",
"lastName": "kumar",
"emailId": "arun#xyz.com",
"mobileNumber": "987654",
"dateOfBirth": "1990-03-02T18:30:00.000+0000",
"gender": "male",
"profilePicture": "Pictures",
"hasTermsAccepted": true,
"dateCreated": "2018-03-02T18:30:00.000+0000",
"dateModified": "2018-03-02T18:30:00.000+0000",
"aadhaarNumber": "565497",
"addressOne": "adyar",
"addressTwo": "chennai",
"pincode": "600096",
"tickets": [],
"active": true,
"firstTimeLogin": true,
"school": true,
"college": true
},
"dateCreated": "2018-03-05T18:30:00.000+0000",
"hasRead": true,
"message": "User 1 has sent a msg to you",
"active": true
}
]
}
Thanks in advance.
I think you should check timezones. It looks like you have saved the date in your local timezone, but when you retrieve it from database and send to client you use GMT timezone.

Getting error with Spring MV 4.0 Restful webservice when I am trying RequestMethod.POST

I am using Postman console to hit service(http://localhost:8080/MyResful/countries1) and it working fine with GET method and giving the following response
[
{
"id": 1,
"countryName": "India",
"population": 10000
},
{
"id": 2,
"countryName": "Pakistan",
"population": 7000
},
{
"id": 3,
"countryName": "Nepal",
"population": 8000
},
{
"id": 4,
"countryName": "China",
"population": 20000
}
]
But it is not working with (http://localhost:8080/MyResful/countries1)POST method and giving the error:
HTTP Status 415, requestThe server refused this request because questing entity is in a format not supported by the requested resource for the requested method ().
In Postman I set header Accept and Content-type "application/JSON"
Please help me on this issue.
I am working with Spring MVC using JSON objects
Here is my controller class:
package com.ness.myrestful.controller;
import java.util.List;
import com.ness.myrestful.bean.Desh;
import com.ness.myrestful.service.DeshService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class CrudRestController {
DeshService countryService = new DeshService();
#RequestMapping(value = "/countries1", method = RequestMethod.GET, headers = "Accept=application/json")
public List<Desh> getCountries() {
List<Desh> listOfCountries = countryService.getAllCountries();
return listOfCountries;
}
#RequestMapping(value = "/country1/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
public Desh getCountryById(#PathVariable int id) {
return countryService.getCountry(id);
}
#RequestMapping(value = "/countries1", method = RequestMethod.POST, headers = "Accept=application/json")
public Desh addCountry(#RequestBody Desh country) {
return countryService.addCountry(country);
}
#RequestMapping(value = "/countries1", method = RequestMethod.PUT, headers = "Accept=application/json")
public Desh updateCountry(#RequestBody Desh country) {
return countryService.updateCountry(country);
}
#RequestMapping(value = "/country1/{id}", method = RequestMethod.DELETE, headers = "Accept=application/json")
public void deleteCountry(#PathVariable("id") int id) {
countryService.deleteCountry(id);
}
}
********************
I am working with Spring MVC using JSON objects
Here is Bean class
package com.ness.myrestful.bean;
public class Desh {
int id;
String countryName;
long population;
public Desh() {
super();
}
public Desh(int i, String countryName,long population) {
super();
this.id = i;
this.countryName = countryName;
this.population=population;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public long getPopulation() {
return population;
}
public void setPopulation(long population) {
this.population = population;
}
}
********************************
I am working with Spring MVC using JSON objects
Here is my service class
package com.ness.myrestful.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.ness.myrestful.bean.Desh;
public class DeshService {
static HashMap<Integer,Desh> countryIdMap=getCountryIdMap();
public DeshService() {
super();
if(countryIdMap==null)
{
countryIdMap=new HashMap<Integer,Desh>();
// Creating some objects of Country while initializing
Desh indiaCountry=new Desh(1, "India",10000);
Desh chinaCountry=new Desh(4, "China",20000);
Desh nepalCountry=new Desh(3, "Nepal",8000);
Desh bhutanCountry=new Desh(2, "Pakistan",7000);
countryIdMap.put(1,indiaCountry);
countryIdMap.put(4,chinaCountry);
countryIdMap.put(3,nepalCountry);
countryIdMap.put(2,bhutanCountry);
}
}
public List<Desh> getAllCountries()
{
List<Desh> countries = new ArrayList<Desh>(countryIdMap.values());
return countries;
}
public Desh getCountry(int id)
{
Desh country= countryIdMap.get(id);
return country;
}
public Desh addCountry(Desh country)
{
country.setId(getMaxId()+1);
countryIdMap.put(country.getId(), country);
return country;
}
public Desh updateCountry(Desh country)
{
if(country.getId()<=0)
return null;
countryIdMap.put(country.getId(), country);
return country;
}
public void deleteCountry(int id)
{
countryIdMap.remove(id);
}
public static HashMap<Integer, Desh> getCountryIdMap() {
return countryIdMap;
}
// Utility method to get max id
public static int getMaxId()
{ int max=0;
for (int id:countryIdMap.keySet()) {
if(max<=id)
max=id;
}
return max;
}
}
Remove header and try consumes.
#RequestMapping(value = "/countries1", method = RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE)
public Desh addCountry(#RequestBody Desh country) {
return countryService.addCountry(country);
}
Proper approach to fix your issue would be a global configuration as you mentioned that you are developing a json based application.
Please add following in you configuration xml file,
<!-- Configure to plugin JSON as request and response in method handler -->
<beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<beans:property name="messageConverters">
<beans:list>
<beans:ref bean="jsonMessageConverter"/>
</beans:list>
</beans:property>
</beans:bean>
<!-- Configure bean to convert JSON to POJO and vice versa -->
<beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</beans:bean>
This will make sure that your JSON request object is converted to and from during server-client communication.
You can then remove the headers from your handler methods in controller.
#RequestMapping(value = "/countries1", method = RequestMethod.POST, headers = "Accept=application/json")
public Desh addCountry(#RequestBody Desh country) {
return countryService.addCountry(country);
}
To,
#RequestMapping(value = "/countries1", method = RequestMethod.POST)
public Desh addCountry(#RequestBody Desh country) {
return countryService.addCountry(country);
}
Also make sure that you have properly add jackson jars in your dependencies as well.