Empty string when using GSON for Java -> JSon - java

Trying to convert a POJO to a Json representation , my output is quite surprising : empty !
Here the POJO class :
public class AccountDTO extends BasicDBObject {
/**
*
*/
public static final String COLLECTION_NAME = "account-data";
private static final long serialVersionUID = 1L;
private String customerFirstName;
private String customerLastName;
private long customerId;
private String IBAN;
private float balance;
private String accountCurrency;
public AccountDTO(Account account, Customer customer) {
super();
this.customerFirstName = customer.getFirstname();
this.customerLastName = customer.getLastname();
this.customerId = customer.getCustomerId();
this.IBAN = account.getIBAN();
this.balance = account.getBalance();
this.accountCurrency = account.getAccountCurrency();
}
public String getCustomerName() {
return customerFirstName;
}
public void setCustomerName(String customerName) {
this.customerFirstName = customerName;
}
public String getCustomerLastName() {
return customerLastName;
}
public void setCustomerLastName(String customerLastName) {
this.customerLastName = customerLastName;
}
public long getCustomerId() {
return customerId;
}
public void setCustomerId(long customerId) {
this.customerId = customerId;
}
public String getIBAN() {
return IBAN;
}
public void setIBAN(String iBAN) {
IBAN = iBAN;
}
public float getBalance() {
return balance;
}
public void setBalance(float balance) {
this.balance = balance;
}
public String getCustomerFirstName() {
return customerFirstName;
}
public void setCustomerFirstName(String customerFirstName) {
this.customerFirstName = customerFirstName;
}
public String getAccountCurrency() {
return accountCurrency;
}
public void setAccountCurrency(String accountCurrency) {
this.accountCurrency = accountCurrency;
}
#Override
public String toString() {
return "AccountDTO [customerFirstName=" + customerFirstName + ", customerLastName=" + customerLastName
+ ", customerId=" + customerId + ", IBAN=" + IBAN + ", balance=" + balance + ", accountCurrency="
+ accountCurrency + "]";
}
}
The converter :
public abstract class AccountDTODigester {
public static String digestJavaToJson(AccountDTO dto){
Gson gson = new Gson();
String json = gson.toJson(dto);
return json;
}
}
Code with jackson :
public abstract class AccountDTODigester {
public static String digestJavaToJson(AccountDTO dto) throws JsonProcessingException{
ObjectMapper mapper = new ObjectMapper();
String jsonInString = new String();
jsonInString = mapper.writeValueAsString(dto);
return jsonInString;
}
}
And finnaly the runner :
public class DAOTest {
AccountDTO accountDTO;
#Before
public void initialize(){
Account account = new Account("FRkk BBBB BGGG GGCC CCCC CCCC CKK", 0, "euro");
Customer customer = new Customer("XXXXXX", "YYYYYY", 1, account);
this.accountDTO = new AccountDTO(account, customer);
}
#Test
public void toJson(){
Assert.assertNotEquals(AccountDTODigester.digestJavaToJson(accountDTO),new String("{}"));
}
Console output :
AccountDTO [customerFirstName=XXXXXX, customerLastName=YYYYYY, customerId=1, IBAN=FRkk BBBB BGGG GGCC CCCC CCCC CKK, balance=0.0, accountCurrency=euro]
{}
When I run the test, my json string is { }and my test is mark as failed.
Gson seems to ver very easy to use, I don't understand why I got this empty Json instead a String filled with a json representation of my AccountDTO object

Ok I found solution :
My JSON was null because extends BasicDBObject , the serialization seems to be jammed by this.
Still looking for a better explication, but now my json is ok.

Related

JSON is returning a list type object when it has 1 position as object and not as a list

I have a list of objects instantiated in a return class in a service's response. But when this list has 1 position, it is returning as an object and not as a list. can anybody help me?
#XmlRootElement(name = "exame")
public class ExameVO implements Serializable {
private static final long serialVersionUID = -5840337332057658386L;
private long id;
#NotNull
private String cpf;
#NotNull
private String dataNascimento;
#NotNull
private int tipoExame;
#NotNull
private String excluido;
private List<ExameArquivoVO> resultadoExameArquivos;
private String observacao;
private String dataInclusao;
public ExameVO() {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(String dataNascimento) {
this.dataNascimento = dataNascimento;
}
public int getTipoExame() {
return tipoExame;
}
public void setTipoExame(int tipoExame) {
this.tipoExame = tipoExame;
}
public String getObservacao() {
return observacao;
}
public void setObservacao(String observacao) {
this.observacao = observacao;
}
public String getExcluido() {
return excluido;
}
public void setExcluido(String excluido) {
this.excluido = excluido;
}
public List<ExameArquivoVO> getResultadoExameArquivos() {
return resultadoExameArquivos;
}
public void setResultadoExameArquivos(List<ExameArquivoVO> resultadoExameArquivos) {
this.resultadoExameArquivos = resultadoExameArquivos;
}
public String getDataInclusao() {
return dataInclusao;
}
public void setDataInclusao(String dataInclusao) {
this.dataInclusao = dataInclusao;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
#Override
public String toString() {
return "ResultadoExameVO [id=" + id + ", cpf=" + cpf + ", dataNascimento=" + dataNascimento + ", tipoExame="
+ tipoExame + ", observacao=" + observacao + ", excluido=" + excluido + ", dataInclusao=" + dataInclusao
+ ", resultadoExameArquivos=" + resultadoExameArquivos + "]";
}
}
#Override
public List<ExameVO> listarExames(String cpf, String dtNascimento, Long tipoExame) throws WebServiceException {
List<ExameVO> examesVO = new ArrayList<ExameVO>();
try {
examesVO = exameDAO.listarExames(cpf, dtNascimento, tipoExame);
if(!examesVO.isEmpty()) {
for(ExameVO exameVO : examesVO) {
exameVO.setResultadoExameArquivos(new ArrayList<ExameArquivoVO>());
exameVO.getResultadoExameArquivos().addAll(exameDAO.listarExameArquivos(exameVO.getId()));
}
}
return examesVO;
} catch (Exception e) {
throw new WebServiceException(e);
}
}
Response to postman: Notice that there is 1 object that has 2 objects inside the file list and another object that has 1 and it returns as an object and not as a list with 1 object.

Unable to parse JSON with Jackson (mapping doesn't work)

I am trying to use Jackson to parse sample json as demonstrated below. However, I the parsing doesn't work (fails without any exceptions - as I get an empty string for event.getAccountId(); What could I be doing wrong?
Thanks!
ObjectMapper om = new ObjectMapper();
String json = "{\"_procurementEvent\" : [{ \"accountId\" : \"3243234\",\"procurementType\" : \"view\"," +
"\"_procurementSubType\" : \"Standard Connector\",\"_quantity\" : \"4\", \"_pricePerMonth\" : \"100.00\"" +
",\"_annualPrice\" : \"1200.00\"}]}";
ProcurementEvent event = om.readValue(json, ProcurementEvent.class);
event.getAccountId(); // returns null
#JsonIgnoreProperties(ignoreUnknown = true)
private static class ProcurementEvent {
private String _accountId;
private String _procurementType;
private String _quantity;
private String _pricePerMonth;
private String _annualPrice;
#JsonProperty("accountId")
public String getAccountId() {
return _accountId;
}
public void setAccountId(String accountId) {
_accountId = accountId;
}
#JsonProperty("procurementType")
public String getProcurementType() {
return _procurementType;
}
public void setProcurementType(String procurementType) {
_procurementType = procurementType;
}
#JsonProperty("_quantity")
public String getQuantity() {
return _quantity;
}
public void setQuantity(String quantity) {
_quantity = quantity;
}
#JsonProperty("_pricePerMonth")
public String getPricePerMonth() {
return _pricePerMonth;
}
public void setPricePerMonth(String pricePerMonth) {
_pricePerMonth = pricePerMonth;
}
#JsonProperty("_annualPrice")
public String getAnnualPrice() {
return _annualPrice;
}
public void setAnnualPrice(String annualPrice) {
_annualPrice = annualPrice;
}
}
In the question, try the following approach:
class ProcurementEvents {
private List<ProcurementEvent> _procurementEvent; // + annotations like #JsonIgnoreProperties, getters/ setters, etc.
}
// json from your example
ProcurementEvents events = om.readValue(json, ProcurementEvents.class);
events.get(0).getAccountId();

How to pull specific object from Json String

I am new to Json Parsing issue I have the below Json object and I need to get the User object from the below Json
{
"aud": "RoomyClinetApps",
"sub": "AAAA",
"User": {
"firtsName": "Godavarthi",
"LastName": "chaitanya"
},
"iss": "Roomy",
"iat": 1499279510
}
The below is the code I am trying to pull the User object where the the above json is in jsonInString variable when i trying t print I am getting null
ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
User user= mapper.readValue(jsonInString.toString(), User.class);
System.out.println(user.getFirtsName()); --> Null
public class User {
#JsonProperty
private String firtsName;
#JsonProperty
private String LastName;
}
Could some one please Provide me a working code which is more appreciable.
Thanks
Chaitanya
Tested the below code. It worked for me. Try this once.
public class Test {
public static void main(String[] args) throws IOException {
String jsonInString = "{\n"
+ " \"aud\": \"RoomyClinetApps\",\n"
+ " \"sub\": \"AAAA\",\n"
+ " \"user\": {\n"
+ " \"firtsName\": \"Godavarthi\",\n"
+ " \"LastName\": \"chaitanya\"\n"
+ " },\n"
+ " \"iss\": \"Roomy\",\n"
+ " \"iat\": 1499279510\n"
+ "}";
ObjectMapper mapper = new ObjectMapper().configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonObject jobj = mapper.readValue(jsonInString.toString(), JsonObject.class);
System.out.println(jobj.getUser().getFirtsName());
}
}
class User {
private String firtsName;
private String LastName;
public String getFirtsName() {
return firtsName;
}
public void setFirtsName(String firtsName) {
this.firtsName = firtsName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String LastName) {
this.LastName = LastName;
}
}
class JsonObject {
private String aud;
private String sub;
private User user;
private String iss;
private long iat;
public String getAud() {
return aud;
}
public void setAud(String aud) {
this.aud = aud;
}
public String getSub() {
return sub;
}
public void setSub(String sub) {
this.sub = sub;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getIss() {
return iss;
}
public void setIss(String iss) {
this.iss = iss;
}
public long getIat() {
return iat;
}
public void setIat(long iat) {
this.iat = iat;
}
}
Hope this is helpful.
public class User {
#JsonProperty
private String firtsName;
#JsonProperty
private String LastName;
}
public class JsonObject{
public string aud;
public String sub;
public User user;
public String iss;
public long iat;
}
ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonObject user= mapper.readValue(jsonInString.toString(), JsonObject.class);

json data should be print in specified textview

I have json data regarding student details,That i want to print in respective textviews. i'm new to json services please help me to print the this data on screen.I'm using getters and setters for subject score so further i want to use them dynamically.
here is my json data
{
"studentInfo": {
"studentName": "srini#gmail.com",
"studentId": "abc",
"date": 14102017,
"JanuaryScoreCard" : {
"english" : "44",
"Science" : "45",
"maths": "66",
"social" : "56",
"hindi" : "67",
"kannada" : "78",
},
"MarchScoreCard" : {
" english " : "54",
" Science " : "56",
" maths ": "70",
" social " : "87",
" hindi " : "98",
" kannada " : "56"
},
"comments" : ""
}
I'm Something to print but could not,i don't where i'm going wrong
public void init()
{
try {
parseJSON();
} catch (JSONException e)
{
e.printStackTrace();
}
}
public void parseJSON() throws JSONException{
jsonObject = new JSONObject(strJson);
JSONObject object = jsonObject.getJSONObject("studentInfo");
patientName = object.getString("studentName");
patientID = object.getString("studentId");
mName.setText(studentName);
mUserId.setText(studentId);
}
You can use JSON parser and then you can print any data you want from that,
Use GSON for this, here is an example https://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
Here is a basic JSON Parsing process
public void parseJson() {
String your_response = "replace this with your response";
try {
JSONObject jsonObject = new JSONObject(your_response);
JSONObject studentInfoJsonObject = jsonObject.getJSONObject("studentInfo");
StudentInfo studentInfo1 = new StudentInfo();
studentInfo1.setStudentName(studentInfoJsonObject.optString("studentName"));
studentInfo1.setStudentId(studentInfoJsonObject.optString("studentId"));
studentInfo1.setDate(studentInfoJsonObject.optString("date"));
studentInfo1.setComments(studentInfoJsonObject.optString("comments"));
JSONObject januaryScoreCardJsonObject = studentInfoJsonObject.optJSONObject("JanuaryScoreCard");
JanuaryScoreCard januaryScoreCard1 = new JanuaryScoreCard();
januaryScoreCard1.setEnglish(januaryScoreCardJsonObject.optString("english"));
januaryScoreCard1.setHindi(januaryScoreCardJsonObject.optString("hindi"));
januaryScoreCard1.setMaths(januaryScoreCardJsonObject.optString("maths"));
januaryScoreCard1.setSocial(januaryScoreCardJsonObject.optString("social"));
januaryScoreCard1.setKannada(januaryScoreCardJsonObject.optString("kannada"));
januaryScoreCard1.setScience(januaryScoreCardJsonObject.optString("Science"));
JSONObject marchScoreCardJsonObject = studentInfoJsonObject.optJSONObject("JanuaryScoreCard");
MarchScoreCard marchScoreCard = new MarchScoreCard();
marchScoreCard.setEnglish(marchScoreCardJsonObject.optString("english"));
marchScoreCard.setHindi(marchScoreCardJsonObject.optString("hindi"));
marchScoreCard.setMaths(marchScoreCardJsonObject.optString("maths"));
marchScoreCard.setSocial(marchScoreCardJsonObject.optString("social"));
marchScoreCard.setKannada(marchScoreCardJsonObject.optString("kannada"));
marchScoreCard.setScience(marchScoreCardJsonObject.optString("Science"));
studentInfo1.setJanuaryScoreCard(januaryScoreCard1);
studentInfo1.setMarchScoreCard(marchScoreCard);
} catch (JSONException e) {
e.printStackTrace();
}
}
Student Info Class
public class StudentInfo {
private String studentName;
private String studentId;
private String date;
private String comments;
private JanuaryScoreCard januaryScoreCard;
private MarchScoreCard marchScoreCard;
public JanuaryScoreCard getJanuaryScoreCard() {
return januaryScoreCard;
}
public void setJanuaryScoreCard(JanuaryScoreCard januaryScoreCard) {
this.januaryScoreCard = januaryScoreCard;
}
public MarchScoreCard getMarchScoreCard() {
return marchScoreCard;
}
public void setMarchScoreCard(MarchScoreCard marchScoreCard) {
this.marchScoreCard = marchScoreCard;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
}
and Here is January class
public class JanuaryScoreCard {
private String english;
private String Science;
private String maths;
private String kannada;
private String social;
private String hindi;
public String getEnglish() {
return english;
}
public void setEnglish(String english) {
this.english = english;
}
public String getScience() {
return Science;
}
public void setScience(String science) {
Science = science;
}
public String getMaths() {
return maths;
}
public void setMaths(String maths) {
this.maths = maths;
}
public String getKannada() {
return kannada;
}
public void setKannada(String kannada) {
this.kannada = kannada;
}
public String getSocial() {
return social;
}
public void setSocial(String social) {
this.social = social;
}
public String getHindi() {
return hindi;
}
public void setHindi(String hindi) {
this.hindi = hindi;
}
}
and Here is March Class
public class MarchScoreCard{
private String english;
private String Science;
private String maths;
private String kannada;
private String social;
private String hindi;
public String getEnglish() {
return english;
}
public void setEnglish(String english) {
this.english = english;
}
public String getScience() {
return Science;
}
public void setScience(String science) {
Science = science;
}
public String getMaths() {
return maths;
}
public void setMaths(String maths) {
this.maths = maths;
}
public String getKannada() {
return kannada;
}
public void setKannada(String kannada) {
this.kannada = kannada;
}
public String getSocial() {
return social;
}
public void setSocial(String social) {
this.social = social;
}
public String getHindi() {
return hindi;
}
public void setHindi(String hindi) {
this.hindi = hindi;
}
}
You need to parse this json Data , For this you need Create appropriate bean classes and put data while parsing json into this bean classes object and create List .
Then you need to create ListView and Adapter for populate data into Screen or Activity.

Get jersey/jackson json into several classes

I have this json response from a server.
{"session_key":"thekey","expires_in":300,"environment":"exttest","country":"SE","private_feed":{"hostname":"priv.api.test.nordnet.se","port":443,"encrypted":true},"public_feed":{"hostname":"pub.api.test.nordnet.se","port":443,"encrypted":true}}
The top level info is parsed fine into the below class. But how do I populate the list of server info?
The code
Response response = baseResource.path("login").queryParam("service", "NEXTAPI")
.queryParam("auth", authParam).request(responseType).post(null);
System.out.println(response);
SessionInfo ses = response.readEntity(SessionInfo.class);
public class SessionInfo {
public String session_key;
public String environment;
public int expires_in;
public String country;
List<ServerInfo> serverInfo = new ArrayList<ServerInfo>();
}
public class ServerInfo {
public String hostname;
public int port;
public boolean encrypted;
}
This works, but I would hope there is a way to convert it in one step since there might be more nested levels in other responses.
ObjectMapper mapper = new ObjectMapper();
ObjectNode json = response.readEntity(ObjectNode.class);
SessionInfo ses = mapper.treeToValue(json, SessionInfo.class);
ServerInfo s1 = mapper.treeToValue(json.get("private_feed"), ServerInfo.class);
ServerInfo s2 = mapper.treeToValue(json.get("public_feed"), ServerInfo.class);
ses.serverInfo.add(s1);
ses.serverInfo.add(s2);
I tried using Jackson, and was able to build the JSON object in one liner. Probably what you are looking for.
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class JackSontest {
public static void main(String[] args){
String jstr = "{\"session_key\":\"thekey\",\"expires_in\":300,\"environment\":\"exttest\",\"country\":\"SE\",\"private_feed\":{\"hostname\":\"priv.api.test.nordnet.se\",\"port\":443,\"encrypted\":true},\"public_feed\":{\"hostname\":\"pub.api.test.nordnet.se\",\"port\":443,\"encrypted\":true}}";
System.out.println("Calling jsonToObject...");
ObjectMapper objectMapper = new ObjectMapper();
try {
SessionInfo info = objectMapper.readValue(jstr, SessionInfo.class);
System.out.println("Session_key:- " + info.getSession_key());
System.out.println("Expires_in:- " + info.getExpires_in());
System.out.println("Environment:- " + info.getEnvironment());
System.out.println("Private Feed:- " + info.getPrivate_feed().getHostname());
System.out.println("Public Feed:- " + info.getPublic_feed().getHostname());
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class SessionInfo {
private String session_key;
private String environment;
private int expires_in;
public String getSession_key() {
return session_key;
}
public void setSession_key(String session_key) {
this.session_key = session_key;
}
public String getEnvironment() {
return environment;
}
public void setEnvironment(String environment) {
this.environment = environment;
}
public int getExpires_in() {
return expires_in;
}
public void setExpires_in(int expires_in) {
this.expires_in = expires_in;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
private String country;
private Feed private_feed;
public Feed getPrivate_feed() {
return private_feed;
}
#JsonProperty("private_feed")
public void setPrivate_feed(Feed private_feed) {
this.private_feed = private_feed;
}
private Feed public_feed;
public Feed getPublic_feed() {
return public_feed;
}
#JsonProperty("public_feed")
public void setPublic_feed(Feed public_feed) {
this.public_feed = private_feed;
}
}
class Feed {
private String hostname;
private int port;
private boolean encrypted;
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public boolean isEncrypted() {
return encrypted;
}
public void setEncrypted(boolean encrypted) {
this.encrypted = encrypted;
}
}
Output:
Calling jsonToObject...
Session_key:- thekey
Expires_in:- 300
Environment:- exttest
Private Feed:- priv.api.test.nordnet.se
Public Feed:- priv.api.test.nordnet.se
have you tried Gson:
public class Employee
{
private Integer id;
private String firstName;
private String lastName;
private List<String> roles;
private Department department; //Department reference
//Other setters and getters
}
class DepartmentInstanceCreator implements InstanceCreator<Department> {
public Department createInstance(Type type)
{
return new Department("None");
}
}
//Now <strong>use the above InstanceCreator</strong> as below
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Department.class, new DepartmentInstanceCreator());
Gson gson = gsonBuilder.create();
System.out.println(
gson.fromJson("{'id':1,'firstName':'Lokesh','lastName':'Gupta','roles':['ADMIN','MANAGER'],'department':{'deptName':'Finance'}}",
Employee.class));
Output:
Employee [id=1, firstName=Lokesh, lastName=Gupta, roles=[ADMIN, MANAGER], department=Department [deptName=Finance]]
source

Categories

Resources