I am using Json to get object details in my POST method to save it in database. The id field is stored correctly but the rest are just taken as null. Can someone point out why.
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.ws.rs.GET;
import javax.ws.rs.*;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.ocpsoft.example.hibernate.model.SimpleObject;
import org.ocpsoft.example.hibernate.util.EntityManagerUtil;
import org.ocpsoft.example.hibernate.dao.SimpleObjectDao;
#Stateless
#Path("/pid")
public class Service {
#GET
#Path("{id}")
public String get(#PathParam("id") long id){
System.out.println("in GET request");
SimpleObjectDao objDao=new SimpleObjectDao();
objDao.startConnection();
SimpleObject obj=objDao.find(id);
objDao.closeConnection();
Gson gson=new Gson();
return gson.toJson(obj);
}
#POST
#Path("/add")
#Consumes("application/json")
//#Produces({MediaType.APPLICATION_JSON})
public String postdata(SimpleObject obj)
{
//SimpleObject obj = (SimpleObject) ob;
//Gson gson=new Gson();
//System.out.println(obj.toString());
//System.out.println("object "+obj.toString());
SimpleObjectDao objDao=new SimpleObjectDao();
objDao.startConnection();
objDao.save(obj);
objDao.closeConnection();
return "Success";
}
}
My object definition is
package org.ocpsoft.example.hibernate.model;
import javax.persistence.*;
import java.io.Serializable;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Column;
import javax.persistence.Version;
import javax.xml.bind.annotation.XmlRootElement;
import java.lang.Override;
/**
* #author Lincoln Baxter, III
*/
#Entity
#XmlRootElement(name="SimpleObject")
public class SimpleObject implements Serializable
{
private static final long serialVersionUID = -2862671438138322400L;
#Id
//#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", updatable = false, nullable = false)
private Long id = null;
//private int Pid;
#Column(name= "Pname")
private String Pname = null;
#Column(name= "Pcost")
private double Pcost = 0.0f;
#Column(name= "Pcat")
private String Pcat = null;
public Long getId()
{
return this.id;
}
public String getPname() {
return Pname;
}
public void setPname(String pname) {
Pname = pname;
}
public double getPcost() {
return Pcost;
}
public void setPcost(double pcost) {
Pcost = pcost;
}
public String getPcat() {
return Pcat;
}
public void setPcat(String pcat) {
Pcat = pcat;
}
public void setId(final Long id)
{
this.id = id;
}
public String toString()
{
String result = "";
if (id != null)
result += id;
return result;
}
#Override
public boolean equals(Object that)
{
if (this == that)
{
return true;
}
if (that == null)
{
return false;
}
if (getClass() != that.getClass())
{
return false;
}
if (id != null)
{
return id.equals(((SimpleObject) that).id);
}
return super.equals(that);
}
#Override
public int hashCode()
{
if (id != null)
{
return id.hashCode();
}
return super.hashCode();
}
}
Apart from Id all the others are not transferred to the object. com where I am going wrong.
I am checking using chrome postman with json as
{ "SimpleObject" :{"id":1,"Pname":"watch","Pcost":200.12,"Pcat":"wearables"}}
Maybe your ID column is auto generate, I think values on POST method cannot cast to your object
Try this :
#POST
#Path("/add")
#Consumes("application/x-www-form-urlencoded")
#Produces(MediaType.APPLICATION_JSON)
public String postdata(MultivaluedMap<String, String> formParams)
we need build SimpleObject object from form params.
hope this help !
Related
I'm trying to create an API for saving a Person and its Address, like in this model:
And i'm getting this error when trying to save an address with a foreing key:
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error:
Cannot construct instance of `com.apitest.api.model.Pessoa` (although at least one Creator exists):
no int/Int-argument constructor/factory method to deserialize from Number value (1)]
I know it seems like a parser error, but it just happens when i do a request that contains the fk field, so:
This is a valid request:
{
"logradouro": "test",
"cep": "354",
"numero": "test",
"cidade": "test"
}
This one i get a 400 bad request:
{
"logradouro": "null",
"cep": "354",
"numero": "null",
"cidade": "null",
"pessoa": 1
}
Just by adding the fk field, like i said.
Models:
Person
package com.apitest.api.model;
import java.util.Date;
import java.util.List;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
#Entity
#Table(name = "pessoa")
public class Pessoa {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column(name = "nome")
private String nome;
#Column(name = "dataNascimento")
private Date dataNascimento;
public Pessoa(Integer id, String nome, Date dataNascimento) {
this.id = id;
this.nome = nome;
this.dataNascimento = dataNascimento;
}
public Pessoa(){
};
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Date getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(Date dataNascimento) {
this.dataNascimento = dataNascimento;
}
}
Address
package com.apitest.api.model;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
#Entity
#Table(name = "endereco")
public class Endereco {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id_endereco;
#Column(name = "logradouro")
private String logradouro;
#Column(name = "cep")
private String cep;
#Column(name = "numero")
private String numero;
#Column(name = "cidade")
private String cidade;
#ManyToOne
#JoinColumn(name = "id")
private Pessoa pessoa;
public Endereco(Integer id_endereco, String logradouro, String cep, String numero, String cidade, Pessoa pessoa) {
this.id_endereco = id_endereco;
this.logradouro = logradouro;
this.cep = cep;
this.numero = numero;
this.cidade = cidade;
this.pessoa = pessoa;
}
public Endereco(){
};
public String getLogradouro() {
return logradouro;
}
public void setLogradouro(String logradouro) {
this.logradouro = logradouro;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public String getCidade() {
return cidade;
}
public void setCidade(String cidade) {
this.cidade = cidade;
}
public Pessoa getPessoa() {
return pessoa;
}
public void setPessoa(Pessoa pessoa) {
this.pessoa = pessoa;
}
public Integer getId_endereco() {
return id_endereco;
}
public void setId_endereco(Integer id_endereco) {
this.id_endereco = id_endereco;
}
}
Controllers:
Person
package com.apitest.api.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.apitest.api.model.Pessoa;
import com.apitest.api.service.PessoaService;
#RestController
public class PessoaController {
#Autowired
private PessoaService pessoaService;
#PostMapping("/pessoas")
public ResponseEntity<Pessoa> createPessoa(#RequestBody Pessoa pessoa){
return ResponseEntity.ok().body(this.pessoaService.createPessoa(pessoa));
}
}
Address
package com.apitest.api.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.apitest.api.model.Endereco;
import com.apitest.api.service.EnderecoService;
#RestController
public class EnderecoController {
#Autowired
private EnderecoService enderecoService;
#PostMapping("/endereco")
public ResponseEntity<Endereco> createEndereco(#RequestBody Endereco endereco){
return ResponseEntity.ok().body(this.enderecoService.createEndereco(endereco));
}
}
Service:
Person
package com.apitest.api.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.apitest.api.model.Pessoa;
import com.apitest.api.repository.PessoaRepository;
#Service
#Transactional
public class PessoaServiceImpl implements PessoaService {
#Autowired
private PessoaRepository pessoaRepository;
#Override
public Pessoa createPessoa(Pessoa pessoa) {
return pessoaRepository.save(pessoa);
}
#Override
public Pessoa updatePessoa(Pessoa pessoa) {
Optional<Pessoa> pessoaDb = this.pessoaRepository.findById(pessoa.getId());
Pessoa pessoaUpdate = pessoaDb.get();
pessoaUpdate.setId(pessoa.getId());
pessoaUpdate.setNome(pessoa.getNome());
return pessoaUpdate;
}
#Override
public Pessoa getPessoaById(Pessoa pessoa) {
// TODO Auto-generated method stub
return null;
}
#Override
public List<Pessoa> getAllPessoa() {
// TODO Auto-generated method stub
return null;
}
#Override
public void deletePessoa(long pessoaId) {
// TODO Auto-generated method stub
}
}
Address
package com.apitest.api.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.apitest.api.model.Endereco;
import com.apitest.api.repository.EnderecoRepository;
import com.apitest.api.repository.PessoaRepository;
import org.springframework.transaction.annotation.Transactional;
#Service
#Transactional
public class EnderecoServiceImpl implements EnderecoService {
#Autowired
private EnderecoRepository enderecoRepository;
#Override
public Endereco createEndereco(Endereco endereco) {
return enderecoRepository.save(endereco);
}
}
I have already tried to use JsonCreator and JsonProperty annotations but did not worked for me...
Any help would be appreciated.
You're getting this error because you're sending the value of "1" for the object Pessoa. You need to pass the fields in the object, something like this should work.
{ "logradouro": "null", "cep": "354", "numero": "null", "cidade": "null", "pessoa": {"id": 1} }
Also, I'm not sure what "null" means here, but if you want those fields to be null, don't send them. The way this is written, you're going to end up with the word null everywhere.
I want to indicate the pathvariable secondpart. Thats not possible because an errormessage shows: Could not determine type for: veranstaltung.Identificationnumber, at table: teilnehmer, for columns: [org.hibernate.mapping.Column(id)]
What I have to change to use the variable secondpart? How can I access the variable secondpart in the method of the Controller?
package veranstaltung;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Teilnehmer {
static int idnumber=69;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Identificationnumber id;
private String name;
private String vorname;
private String wohnort;
protected Teilnehmer() {}
public Teilnehmer(Identificationnumber id, String name, String vorname,String wohnort)
{
this.id=id;
this.name=name;
this.vorname=vorname;
this.wohnort=wohnort;
}
public static String erzeugeID ()
{
String id= "JAVALAND-";
id=id+idnumber;
idnumber++;
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVorname() {
return vorname;
}
public void setVorname(String vorname) {
this.vorname = vorname;
}
public String getWohnort() {
return wohnort;
}
public void setWohnort(String wohnort) {
this.wohnort = wohnort;
}
#Override
public String toString()
{
return id.getfullID()+" "+getName()+" "+getVorname()+" "+getWohnort();
}
}
package veranstaltung;
public class Identificationnumber {
private String firstpart;
private Long secondpart;
public Identificationnumber(String firstpart, Long secondpart)
{
this.firstpart=firstpart;
this.secondpart=secondpart;
}
public String getFirstpart() {
return firstpart;
}
public void setFirstpart(String firstpart) {
this.firstpart = firstpart;
}
public Long getSecondpart() {
return secondpart;
}
public void setSecondpart(Long secondpart) {
this.secondpart = secondpart;
}
public String getfullID()
{
return firstpart+' '+secondpart;
}
}
package veranstaltung;
import veranstaltung.Teilnehmer;
import veranstaltung.Identificationnumber;
import veranstaltung.TeilnehmerRepository;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
#RestController
public class TeilnehmerController {
#Autowired
TeilnehmerRepository teilnehmerRepository;
#GetMapping("/teilnehmer")
Iterable<Teilnehmer> teilnehmer(){
return this.teilnehmerRepository.findAll();
}
#GetMapping("/teilnehmer/{id}")
Teilnehmer teilnehmerById(#PathVariable Long secondpart){
Optional<Teilnehmer> teilnehmerOptional = this.teilnehmerRepository.findById(secondpart);
if(teilnehmerOptional.isPresent()) {
return teilnehmerOptional.get();
}
return null;
}
}
Your Identificationnumber is not primitive but custom class. What you are doing is trying to use Long against your Identificationnumber in teilnehmerById method.
I would suggest to either change #Id column of Teilnehmer to Long from Identificationnumber or you can still pass Identificationnumber in teilnehmerById method by doing something like below (This is based on consideration that you have implemented your own findById which will convert Identificationnumber to Long):
#GetMapping("/teilnehmer/{id}")
Teilnehmer teilnehmerById(#PathVariable Long secondpart){
Identificationnumber number = new Identificationnumber();
number.setSecondpart(secondpart);
Optional<Teilnehmer> teilnehmerOptional = this.teilnehmerRepository.findById(number.getfullID());
if(teilnehmerOptional.isPresent()) {
return teilnehmerOptional.get();
}
return null;
Based on hibernate error, it looks like you have to use my first option which is change #Id of Teilnehmer to Long.
Edit : just updated code so that you can use composition of String to Long.
I have a problem in accessing get method of a generic class in REST API project. there are no errors but it returns null. here I mention the code. The idea working fine when I implemented without REST API. Insert and GetALL methods are working fine in REST API but problem is Repo class Get method couldn't work with REST.
package lk.ac.jfn.vau.DeptApi.Model;
public class Department extends PrimaryID<Long>{
private String Name;
private String Location;
public Department() {
//super();
}
public Department(long id, String name, String location) {
super(id);
Name = name;
Location = location;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getLocation() {
return Location;
}
public void setLocation(String location) {
Location = location;
}
}
package lk.ac.jfn.vau.DeptApi.Model;
public class PrimaryID<U> {
private U Id;
public PrimaryID() {
}
public PrimaryID(U id) {
Id = id;
}
public U getId() {
return Id;
}
public void setId(U id) {
Id = id;
}
}
package lk.ac.jfn.vau.DeptApi.Repo;
import java.util.ArrayList;
import java.util.List;
import lk.ac.jfn.vau.DeptApi.Model.PrimaryID;
public class Repo<T extends PrimaryID<U>,U> {
List<T> list= new ArrayList<T>();
public List<T> getAll(){
return list;
}
public void insert(T obj) {
list.add(obj);
}
public T get(U id) {
for(T obj:list) {
//objects are there
System.out.println(obj);
//but getId returns null
if(obj.getId().equals(id)) {
return obj;
}
}
return null;
}
public void Delete(U id) {
list.remove(get(id));
}
public void Update(U id,T obj) {
list.set(list.indexOf(get(id)), obj);
}
}
package lk.ac.jfn.vau.DeptApi.Repo;
import lk.ac.jfn.vau.DeptApi.Model.Department;
public class DepartmentRepo extends Repo<Department, Long> {
}
package lk.ac.jfn.vau.DeptApi;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import lk.ac.jfn.vau.DeptApi.Model.Department;
import lk.ac.jfn.vau.DeptApi.Repo.DepartmentRepo;
#Path("/dept")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public class DepartmentResource {
private static DepartmentRepo repo = new DepartmentRepo();
#GET
public List<Department> getDepartments() {
return repo.getAll();
}
#POST
public void addDepartment(Department department) {
repo.insert(department);
}
#GET
#Path("/{id}")
public Department getDepartment(#PathParam("id") long id) {
return repo.get(id);
}
#DELETE
#Path("/{id}")
public void deleteDepartment(#PathParam("id") long id) {
repo.Delete(id);
}
}
I found the problem. Problem is Object to JSON conversion. when I updated the JSON library it worked fine.
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-json-jackson -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
</dependency>
I have already created a restful api using java and glassfish but I'm facing a problem (not an error).
When I receive the JSON response from my API it works fine but contains the name of the beans.
{"***countriesBean***":[ //(I need my response without this field)
{"CountryID":"3","CountryName":"asdasdasd","DefaultCurrencyID":"0","DefaultLanguageID":"0"},{"CountryID":"16","CountryName":"sddd","DefaultCurrencyID":"1","DefaultLanguageID":"0"},{"CountryID":"1","CountryName":"Lebanon","DefaultCurrencyID":"3","DefaultLanguageID":"0"},{"CountryID":"2","CountryName":"asdasd","DefaultCurrencyID":"0","DefaultLanguageID":"2"}
]
}
this is the bean
package beans;
import javax.ws.rs.FormParam;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author ahmad.s
*/
#XmlRootElement
#XmlAccessorType(XmlAccessType.NONE)
public class CountriesBean {
// #XmlElement
#XmlElement(name="CountryID")
private Integer COUNTRY_ID;
#XmlElement(name="CountryName")
private String COUNTRY_NAME;
#XmlElement(name="LanguageID")
private Integer LANGUAGE_ID;
#XmlElement(name="DefaultCurrencyID")
private Integer DEFAULT_CURRENCY_ID;
#XmlElement(name="DefaultLanguageID")
private Integer DEFAULT_LANGUAGE_ID;
#XmlElement(name="TaskID")
private Integer TASK_ID;
#XmlElement(name="CurrencyID")
private Integer CURRENCY_ID;
public Integer getCURRENCY_ID() {
return CURRENCY_ID;
}
public void setCURRENCY_ID(Integer CURRENCY_ID) {
this.CURRENCY_ID = CURRENCY_ID;
}
public Integer getTASK_ID() {
return TASK_ID;
}
public void setTASK_ID(Integer TASK_ID) {
this.TASK_ID = TASK_ID;
}
public Integer getDEFAULT_LANGUAGE_ID() {
return DEFAULT_LANGUAGE_ID;
}
public void setDEFAULT_LANGUAGE_ID(Integer DEFAULT_LANGUAGE_ID) {
this.DEFAULT_LANGUAGE_ID = DEFAULT_LANGUAGE_ID;
}
public Integer getDEFAULT_CURRENCY_ID() {
return DEFAULT_CURRENCY_ID;
}
public void setDEFAULT_CURRENCY_ID(Integer DEFAULT_CURRENCY_ID) {
this.DEFAULT_CURRENCY_ID = DEFAULT_CURRENCY_ID;
}
public Integer getCOUNTRY_ID() {
return COUNTRY_ID;
}
public void setCOUNTRY_ID(Integer COUNTRY_ID) {
this.COUNTRY_ID = COUNTRY_ID;
}
public String getCOUNTRY_NAME() {
return COUNTRY_NAME;
}
public void setCOUNTRY_NAME(String COUNTRY_NAME) {
this.COUNTRY_NAME = COUNTRY_NAME;
}
public Integer getLANGUAGE_ID() {
return LANGUAGE_ID;
}
public void setLANGUAGE_ID(Integer LANGUAGE_ID) {
this.LANGUAGE_ID = LANGUAGE_ID;
}
}
this the Countries Service Class
package service;
import beans.CountriesBean;
import com.xperteam.DBC.DataBaseConnection;
import entity.Countries;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
/**
*
* #author ahmad.s
*/
#Stateless
#Path("countries")
public class CountriesFacadeREST extends AbstractFacade<Countries> {
#PersistenceContext(unitName = "WeddingRestApiPU")
private EntityManager em;
public CountriesFacadeREST() {
super(Countries.class);
}
#POST
#Override
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public void create(Countries entity) {
super.create(entity);
}
#PUT
#Path("{id}")
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public void (#PathParam("id") Long id, Countries entity) {
super.(entity);
}
#DELETE
#Path("{id}")
public void remove(#PathParam("id") Long id) {
super.remove(super.find(id));
}
#GET
#Path("{id}")
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Countries find(#PathParam("id") Long id) {
return super.find(id);
}
#GET
#Override
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public List<Countries> findAll() {
return super.findAll();
}
#GET
#Path("{from}/{to}")
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public List<Countries> findRange(#PathParam("from") Integer from, #PathParam("to") Integer to) {
return super.findRange(new int[]{from, to});
}
#GET
#Path("count")
#Produces(MediaType.TEXT_PLAIN)
public String countREST() {
return String.valueOf(super.count());
}
#Override
protected EntityManager getEntityManager() {
return em;
}
#GET
#Path("/getAllCountries") // webresources/beans.contactbean/getContactID?ContactID=? get contact info by id
#Produces(MediaType.APPLICATION_JSON)
public ArrayList<CountriesBean> getAllCountries() {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
ArrayList<CountriesBean> CountriesList = new ArrayList<CountriesBean>();
CountriesBean CountriesBean = null;
StringBuffer query = new StringBuffer();
query.append(" SELECT ");
query.append(" COUNTRIES.COUNTRY_ID, ");
query.append(" COUNTRIES_TRANS.COUNTRY_TRANS_NAME,COUNTRIES.DEFAULT_CURRENCY_ID,COUNTRIES.DEFAULT_LANGUAGE_ID ");
query.append(" FROM COUNTRIES INNER JOIN COUNTRIES_TRANS ON COUNTRIES_TRANS.COUNTRY_ID=COUNTRIES.COUNTRY_ID ");
query.append(" WHERE COUNTRIES_TRANS.LANGUAGE_ID = 1 ");
int counter = 1;
try {
DataBaseConnection DataBaseConnection = new DataBaseConnection();
Connection con = DataBaseConnection.GetConnection();
preparedStatement = con.prepareStatement(new String(query));
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
CountriesBean = new CountriesBean();
CountriesBean.setCOUNTRY_ID(resultSet.getInt("COUNTRY_ID"));
CountriesBean.setCOUNTRY_NAME(resultSet.getString("COUNTRY_TRANS_NAME"));
CountriesBean.setDEFAULT_CURRENCY_ID(resultSet.getInt("DEFAULT_CURRENCY_ID"));
CountriesBean.setDEFAULT_LANGUAGE_ID(resultSet.getInt("DEFAULT_LANGUAGE_ID"));
CountriesList.add(CountriesBean);
}
con.close();
} catch (SQLException sqlException) {
CountriesList = null;
System.out.println("getWeddingType : " + sqlException.getMessage());
} catch (NamingException ex) {
Logger.getLogger(CountriesFacadeREST.class.getName()).log(Level.SEVERE, null, ex);
} finally {
query = null;
try {
if (resultSet != null) {
resultSet.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
} catch (Exception exception) {
}
}
return CountriesList;
}
}
I cannot verify your problem without your code.
Please see a basic example with your expectation:
public class Customer {
String fullName;
String email;
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Customer{" +
"fullName='" + fullName + '\'' +
", email='" + email + '\'' +
'}';
}
}
..
#Path("/services")
public class MaisonService {
#GET
#Path("/test")
#Produces(MediaType.APPLICATION_JSON)
public Customer getSampleCustomer() {
Customer sampleCustomer = new Customer();
sampleCustomer.setFullName("Trinh Toan Trung");
sampleCustomer.setEmail("trinhtoantrung#gmail.com");
return sampleCustomer;
}
..
The output:
{"email":"trinhtoantrung#gmail.com","fullName":"Trinh Toan Trung"}
There are many simple ways to do it, following is the most simplest as you are able to get the response as your POJO or DTO clas
MyResponse ob = new ObjectMapper().readValue(jsonString, MyResponse.class);
Am writing an Webservice endpoint which will produce JSON and XML response. Here i would like to convert an object to JSON and setting it to string. When i try to do with the below code
Webservice Endpoint
package com.test1;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;`
#Path("v1")
public class Impl1 {
#POST
#Path("method")
#Produces({"text/xml","application/json"})
public XML method() throws JSONException
{
//JSONObject obj = new JSONObject();
JSONArray ary = new JSONArray();
Main main = new Main();`
List<Student> details = new ArrayList<Student>() ;
Student s1 = new Student();
Student s2 = new Student();
Student s3 = new Student();
s1.setId("ID1");
s1.setValue("1");
s2.setId("ID2");
s2.setValue("2");
s3.setId("ID3");
s3.setValue("3");
details.add(s1);
details.add(s2);
details.add(s3);
main.setDetails(details);
ary.put(details);
Employee emp = new Employee();
emp.setName("Mike");
emp.setSalary(1000);
XML xml = new XML();
xml.setDetails(ary.toString());
xml.setEmp(emp);
xml.setId("1");
return xml;
}
}
XML class (JAXB)
package com.test1;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class XML {
String id;
Employee emp;
String details;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Employee getEmp() {
return emp;
}
public void setEmp(Employee emp) {
this.emp = emp;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
}
Student Class
package com.test1;
public class Student {
String id;
String Value;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getValue() {
return Value;
}
public void setValue(String value) {
Value = value;
Main Class
package com.test1;
import java.util.List;
public class Main {
List<Student> details;
public List<Student> getDetails() {
return details;
}
public void setDetails(List<Student> details) {
this.details = details;
}
}
So when i hit my service am getting response as
{
"details" : "[[{\"id\":\"ID1\",\"value\":\"1\"},{\"id\":\"ID2\",\"value\":\"2\"},{\"id\":\"ID3\",\"value\":\"3\"}]]",
"emp" : {
"name" : "Arun",
"salary" : "1000.0"
},
"id" : "1"
}
Expected String valuse as
[{"id":"ID1","value":"1"},{"id":"ID2","value":"2"},{"id":"ID3","value":"3"}]
My Question is Why JSONArray which was converted as String contains "\" on every key value pair. is there any way to overcome this?
Use Jackson or google-gson or any other library.
For example
http://howtodoinjava.com/2014/06/16/jackson-examples-convert-java-object-to-from-json/