Jackson JSON Can not construct instance of "About" : deserialize issue - json

I've make HttpsURLConnection to receive some information about my server.
The result of response is :
{"about":{"title":"NiFi","version":"1.1.0","uri":"https://localhost:443/api/","contentViewerUrl":"/nifi-content-viewer/","timezone":"CET"}}
How is possible to extract all attributes and key/value ?
About.class file
public class About {
private List<AboutObject> about;
public About()
{
// this.about = about;
}
public List<AboutObject> getAbout() {
return this.about;
}
public void setAbout(List<AboutObject> about) {
this.about = about;
}
}
AboutObject.class
public class AboutObject {
private String title;
private String uri;
private String contentViewerUrl;
private String timezone;
public String getTitle()
{
return this.title;
}
public void setTitle(String title)
{
this.title = title;
}
public String getUri()
{
return this.uri;
}
public void setUri(String uri)
{
this.uri = uri;
}
public String getContentViewerUrl()
{
return this.contentViewerUrl;
}
public void setContentViewerUrl(String contentViewerUrl)
{
this.contentViewerUrl = contentViewerUrl;
}
public String getTimeZone()
{
return this.timezone;
}
public void setTimeZone(String timezone)
{
this.timezone = timezone;
}
}
Main.class
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
System.out.println("Contenu de in = " + in.toString());
ObjectMapper mapper = new ObjectMapper();
//Staff objStaff = new Staff();
System.out.println("Object to JSON in file");
mapper.writeValue(new File("output/file.json"), response);
System.out.println("Convert JSON string from file to Object");
//String about = mapper.readValue(new File("output/file.json"), String.class);
About about = mapper.readValue(new File("output/file.json"), About.class);
Error
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of About: no String-argument constructor/factory method to deserialize from String value ('{"about":{"title":"NiFi","version":"1.1.0","uri":"https://localhost:443/api/","contentViewerUrl":"/nifi-content-viewer/","timezone":"CET"}}') at [Source: output/file.json; line: 1, column: 1]
Thanks for you help

The test json you show doesn't have the array wrapper used in your About object. You're also missing the version field in your AboutObject and the timezone field uses the wrong case.
Your example worked when I updated your objects:
public class About {
private AboutObject about;
public AboutObject getAbout() {
return about;
}
public void setAbout(AboutObject about) {
this.about = about;
}
}
public class AboutObject {
private String title;
private String uri;
private String contentViewerUrl;
private String timezone;
private String version;
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUri() {
return this.uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getContentViewerUrl() {
return this.contentViewerUrl;
}
public void setContentViewerUrl(String contentViewerUrl) {
this.contentViewerUrl = contentViewerUrl;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
Test:
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String obj = "{\"about\":{\"title\":\"NiFi\",\"version\":\"1.1.0\",\"uri\":\"https://localhost:443/api/\",\"contentViewerUrl\":\"/nifi-content-viewer/\",\"timezone\":\"CET\"}}";
About about = mapper.readValue(obj, About.class);
}

Related

Exception : java.util.LinkedHashMap cannot be cast to com.excel.entity.ClassA

This is the generic method through which i am accepting list of
objects and downcasting to a specific object
public Response generate(List<?> list){
List<ClassA> List1 = new ArrayList<ClassA>();
List<ClassB> List2 = new ArrayList<ClassB>();
List<ClassC> List3 = new ArrayList<ClassC>();
if(list instanceof List<?>){
List1=(List<ClassA>) list;//in this line i am getting error
addDataToExcel(List1);
}
else if(list instanceof List<?>){
List2=(List<ClassB>) list;
addDataToExcel(List1);
}
else if(list instanceof List<?>){
List3=(List<ClassC>) list;
addDataToExcel(List1);
}
This is classA
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
#Entity
#Table(name="ClassA")
public class ClassA {
#Id
#Column(name="rollNo")
private int rollNo;
#Column(name="name")
private String name;
#Column(name="english")
private double english;
#Column(name="maths")
private double maths;
#Column(name="science")
private double science;
#Column(name="totalMarks")
private double totalMarks;
#Column(name="percentage")
private double percentage;
#Column(name="status")
private boolean status;
#Lob
#Column(name="file", columnDefinition="BLOB")
private byte[] file;
public ClassA() {
// TODO Auto-generated constructor stub
}
public ClassA(int rollNo, String name, double english, double maths, double science, double totalMarks,
double percentage, boolean status, byte[] file) {
super();
this.rollNo = rollNo;
this.name = name;
this.english = english;
this.maths = maths;
this.science = science;
this.totalMarks = totalMarks;
this.percentage = percentage;
this.status = status;
this.file = file;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getEnglish() {
return english;
}
public void setEnglish(double english) {
this.english = english;
}
public double getMaths() {
return maths;
}
public void setMaths(double maths) {
this.maths = maths;
}
public double getScience() {
return science;
}
public void setScience(double science) {
this.science = science;
}
public double getTotalMarks() {
return totalMarks;
}
public void setTotalMarks(double totalMarks) {
this.totalMarks = totalMarks;
}
public double getPercentage() {
return percentage;
}
public void setPercentage(double percentage) {
this.percentage = percentage;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public byte[] getFile() {
return file;
}
public void setFile(byte[] file) {
this.file = file;
}
}
This is the method which accepts List and generate excel
public void add(List<ClassA> classA) {
System.out.println("entering add");
String excelFilePath = "D:/eclipse_neon/StudentInfo.xlsx";
try {
FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
int rowNum = 1;
int a=2;
for(ClassA info: classA){
System.out.println("netering loop");
Row row = sheet.getRow(rowNum++);
row.createCell(2).setCellValue(info.getEnglish());
row.createCell(3).setCellValue(info.getMaths());
row.createCell(4).setCellValue(info.getScience());
row.createCell(5).setCellFormula("SUM(C"+a+","+"D"+a+","+"E"+a+")");
row.createCell(6).setCellFormula("("+"F"+a+"*"+"100"+")"+"/"+"300");
row.createCell(7).setCellValue(info.isStatus());
a++;
}
System.out.println("after for loop");
inputStream.close();
FileOutputStream outputStream = new FileOutputStream("D:/eclipse_neon/StudentInfo.xlsx");
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException | EncryptedDocumentException
| InvalidFormatException ex) {
ex.printStackTrace();
}
}
I am not able to downcast to my specific List of class from generic list soo any suggestions are welcomed Thankyou
That's probably because you're sending a list as parameter containing a List and class A is not related to LinkedHashMap (not a subclass for example) and therefore it cannot cast. If you can provide more details what is class A and what is the list you're sending as arguments to your method.
Check https://www.baeldung.com/java-type-casting

How to retrieve field value from json object when object name has DOT in it

I want to extract "msg" value from below json using fasterxml.jackson - Can anyone suggest me how my model class should look like?
{
"statusCode": 422,
"error": "Unprocessable Entity",
"message": "Bad data received",
"err_data": {
"payment_details.type": {
"location": "body",
"param": "payment_details.type",
"msg": "Must be either etransfer or cheque"
}
}
}
This is what I have done, but it is always returning "null" !
#JsonInclude(JsonInclude.Include.ALWAYS)
public class MyApiResponse extends ParentResponse implements Serializable {
private static final long serialVersionUID = 1L;
#JsonProperty("payment_details")
private PaymentDetails payment_details;
#JsonProperty("payment_details")
public PaymentDetails getPayment_details() {
return payment_details;
}
#JsonProperty("payment_details")
public void setPayment_details(PaymentDetails payment_details) {
this.payment_details = payment_details;
}
}
ParentResponse model class extends ErrorResponse model class and this is how it looks like..
This ErrorResponse model represents above mentioned JSON.
#JsonInclude(JsonInclude.Include.NON_NULL)
public class ErrorResponse implements Serializable {
private static final long serialVersionUID = 1L;
#JsonProperty("statusCode")
private int statusCode;
#JsonProperty("error")
private String error;
#JsonProperty("message")
private String message;
#JsonProperty("err_data")
private ErrData err_data;
#JsonProperty("statusCode")
public int getStatusCode() {
return statusCode;
}
#JsonProperty("statusCode")
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
#JsonProperty("message")
public String getMessage() {
return message;
}
#JsonProperty("message")
public void setMessage(String message) {
this.message = message;
}
#JsonProperty("error")
public String getError() {
return error;
}
#JsonProperty("error")
public void setError(String error) {
this.error = error;
}
#JsonProperty("err_data")
public ErrData getErr_data() {
return err_data;
}
#JsonProperty("err_data")
public void setErr_data(ErrData err_data) {
this.err_data = err_data;
}
}
err_data object is represented by below model class.
#JsonInclude(JsonInclude.Include.ALWAYS)
public class ErrData implements Serializable {
private static final long serialVersionUID = 1L;
#JsonProperty("email")
private Email email;
#JsonProperty("payment_details.type")
private PaymentDetailsType payment_details_type;
#JsonProperty("email")
public Email getEmail() {
return email;
}
#JsonProperty("email")
public void setEmail(Email email) {
this.email = email;
}
#JsonProperty("payment_details.type")
public PaymentDetailsType getPayment_details_type() {
return payment_details_type;
}
#JsonProperty("payment_details.type")
public void setPayment_details_type(PaymentDetailsType payment_details_type) {
this.payment_details_type = payment_details_type;
}
}
payment_details.type object represented by below class.
#JsonInclude(JsonInclude.Include.ALWAYS)
public class PaymentDetailsType extends ErrorMessage implements Serializable {
private static final long serialVersionUID = 1L;
}
#JsonInclude(JsonInclude.Include.ALWAYS)
public class Email extends ErrorMessage implements Serializable {
private static final long serialVersionUID = 1L;
}
And finally ErrorMessage which is extended by PaymentDetailsType as below.
#JsonPropertyOrder({"location", "param", "value", "msg"})
public class ErrorMessage implements Serializable {
private static final long serialVersionUID = 1L;
#JsonProperty("location")
private String location;
#JsonProperty("param")
private String param;
#JsonProperty("value")
private String value;
#JsonProperty("msg")
private String msg;
#JsonProperty("location")
public String getLocation() {
return location;
}
#JsonProperty("location")
public void setLocation(String location) {
this.location = location;
}
#JsonProperty("param")
public String getParam() {
return param;
}
#JsonProperty("param")
public void setParam(String param) {
this.param = param;
}
#JsonProperty("value")
public String getValue() {
return value;
}
#JsonProperty("value")
public void setValue(String value) {
this.value = value;
}
#JsonProperty("msg")
public String getMsg() {
return msg;
}
#JsonProperty("msg")
public void setMsg(String msg) {
this.msg = msg;
}
}
And finally I am trying to get "msg" field value as below -
new Gson().fromJson(response.asString(), MyApiResponse.class).getErr_data().getPayment_details_type().getMsg();
I think there is something wrong with this one - Not sure how to define getter method if field name in json as . (dot).
#JsonProperty("payment_details.type")
public PaymentDetailsType getPayment_details_type() {
return payment_details_type;
}
Similar to above, I am doing it for below json to retrieve "msg" value and it is working fine.
{
"statusCode": 422,
"error": "Unprocessable Entity",
"message": "Bad data received",
"err_data": {
"email": {
"location": "body",
"param": "email",
"value": "test # com",
"msg": "Must be a valid email"
}
}
}
This is returning correct "msg" value.
new Gson().fromJson(response.asString(), MyApiResponse.class).getErr_data().getEmail().getMsg();
Please suggest!
Thank you.
Here is a minimal example showing how to parse a JSON with Jackson, where the property names may contain dots:
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
class Main {
public static void main(String[] args) throws IOException {
String json = "{" +
" \"payment_details.type\": {" +
" \"location\": \"body\"" +
" }" +
"}";
ObjectMapper mapper = new ObjectMapper();
Response response = mapper.readValue(json, Response.class);
System.out.println(response.getPaymentDetailsType().getLocation());
}
}
class Response {
#JsonProperty("payment_details.type")
private PaymentDetailsType paymentDetailsType;
public PaymentDetailsType getPaymentDetailsType() { return paymentDetailsType; }
}
class PaymentDetailsType {
private String location;
public String getLocation() { return location; }
}
Note that you only need #JsonProperty when the expected property name in JSON cannot be deduced from a setter or variable name
Its also working with #JsonProperty.
You just have to escape the dot:
#JsonProperty("payment_details\\.type")

Spring Framework Default Error Page to JSON

Sorry,
if i am asking for lazy solution.
#SpringBootConfiguration
public class RestWebApplication {
public static void main(String[] args) {
SpringApplication.run(RestWebApplication.class, args);
}
}
But when nothing is implemented, I expected
$ curl localhost:8080
{"timestamp":1384788106983,"error":"Not Found","status":404,"message":""}
But Got
<!DOCTYPE html><html><head><title>Apache Tomcat/8.5.9 - Error report</title><style type="text/css">h1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style> </head><body><h1>HTTP Status 404 - /</h1><div class="line"></div><p><b>type</b> Status report</p><p><b>message</b> <u>/</u></p><p><b>description</b> <u>The requested resource is not available.</u></p><hr class="line"><h3>Apache Tomcat/8.5.9</h3></body></html>
Did i miss something ?
So that i the error page is redirected as JSON Output?
Thanks in credit for your help.
You can try to use #ControllerAdvice that help for custom exception handling in spring.
This is the code I use :
#ControllerAdvice
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler()
public ResponseEntity<Exception> defaultErrorHandler(Exception e) throws Exception {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
#ExceptionHandler()
public ResponseEntity<ShemoException> defaultErrorHandler(ShemoException e) throws Exception {
return new ResponseEntity<>(e,HttpStatus.NOT_FOUND);
}
This is custom Exception class:
import com.google.gson.JsonSyntaxException;
public class ShemoResponseMessage {
private int returnCode;
private String returnStatus;
private String errorSource;
// constructor
public ShemoResponseMessage() {
returnCode = -1;
returnStatus = null;
errorSource = null;
}
// Constructor with individual response parts
public ShemoResponseMessage(int code, String status, String source) {
returnCode = code;
returnStatus = status;
errorSource = source;
}
public ShemoResponseMessage(String shemoResponse) {
this();
if (shemoResponse == null) {
return;
}
ShemoResponseMessage obj = null;
try {
obj = (ShemoResponseMessage) GsonUtils.createGson().fromJson(shemoResponse,
ShemoResponseMessage.class);
} catch (JsonSyntaxException e) {
returnCode = -1;
returnStatus = "";
errorSource = "";
return;
}
returnCode = obj.returnCode;
returnStatus = obj.returnStatus;
errorSource = obj.errorSource;
}
public ShemoResponseMessage(ShemoException e) {
this(e.getMessage());
}
// Copy constructor
public ShemoResponseMessage(ShemoResponseMessage obj) {
this(obj.getReturnCode(), obj.getReturnStatus(), obj.getErrorSource());
}
// getters
public int getReturnCode() {
return returnCode;
}
public String getReturnStatus() {
return returnStatus;
}
public String getErrorSource() {
return errorSource;
}
// Get the json error message back. Creates a formatted message which can be used for throwing API exceptions
public String getShemoExeption() {
String jsonResponse = GsonUtils.createGson().toJson(this, ShemoResponseMessage.class);
return jsonResponse;
}
}
You can return any message you like
UPDATED
This is my custom exception class you can modify it per your need:
public class ShemoException extends Exception {
private static final long serialVersionUID = 1L;
Integer errorCode;
String errorMessage;
public ShemoException(Exception e) {
super(e);
errorCode = -1;
errorMessage = "";
String classNameMessage = getExceptionClassName(e);
if (e.getMessage() != null)
errorMessage = classNameMessage + ", " + e.getMessage();
else
errorMessage = classNameMessage;
}
private String getExceptionClassName(Exception e) {
String className = new String();
String classNameMessage = new String("");
Class<? extends Exception> eClass = e.getClass();
if (eClass != null) {
className = eClass.getSimpleName();
String words[] = className.split("(?=[A-Z])"); // Split Name by Upper Case for readability
// put the Name back together, now with spaces between words
for (int i = 0; i < words.length; i++) {
String word = words[i];
if (i > 0 && word.length() > 1)
classNameMessage = classNameMessage.concat(" ");
classNameMessage = classNameMessage.concat(word);
}
}
return classNameMessage.trim();
}
public ShemoException(Integer errorCode, String errorMessage) {
super();
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
public ShemoException(Integer errorCode, ShemoResponseMessage responseMessage) {
super();
this.errorCode = errorCode;
this.errorMessage = responseMessage.getShemoExeption();
}
public Integer getErrorCode() {
return errorCode;
}
public void setErrorCode(Integer errorCode) {
this.errorCode = errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
#Override
public String getMessage() {
return getErrorMessage();
}
}
GsonUtils class:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* Created by Shemo on 11/24/2015.
*/
public class GsonUtils {
public static String defaultDateTimeFormat = "yyyy-MM-dd'T'HH:mm:ssZ";
private static GsonBuilder gsonBuilder = new GsonBuilder().setDateFormat(defaultDateTimeFormat);
/***
* Creates a GSON instance from the builder with the default date/time format
*
* #return the GSON instance
*/
public static Gson createGson() {
// Create with default params
gsonBuilder = gsonBuilder.setDateFormat(defaultDateTimeFormat);
return gsonBuilder.create();
}
/***
* Creates a GSON instance from the builder specifying custom date/time format
*
* #return the GSON instance
*/
public static Gson createGson(String dateTimeFormat) {
// Create with the specified dateTimeFormat
gsonBuilder = gsonBuilder.setDateFormat(dateTimeFormat);
return gsonBuilder.create();
}
}
GSON library:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>

org.codehaus.jackson.JsonGenerationException: Can not write number, expecting field name

Hi i am working on a spring mvc application well i need to Serialize an object in order to pass it with an ajax Post.
my bean class :
#JsonSerialize(using = AgentSer.class)
public class AgentCust implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Long personneID;
private String nom;
private String prenom;
private String matriculation;
private String marche;
private String compte;
private String phone, mail, chat;
public String getMarche() {
return marche;
}
public void setMarche(String marche) {
this.marche = marche;
}
public String getCompte() {
return compte;
}
public void setCompte(String compte) {
this.compte = compte;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getChat() {
return chat;
}
public void setChat(String chat) {
this.chat = chat;
}
public Long getPersonneID() {
return personneID;
}
public void setPersonneID(Long personneID) {
this.personneID = personneID;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getMatriculation() {
return matriculation;
}
public void setMatriculation(String matriculation) {
this.matriculation = matriculation;
}
}
and the class that will serialize my bean :
public class AgentSer extends JsonSerializer<AgentCust> {
#Override
public void serialize(AgentCust value, JsonGenerator jgen, SerializerProvider arg2) throws IOException, JsonProcessingException {
// TODO Auto-generated method stub
jgen.writeStartObject();
jgen.writeNumber(value.getPersonneID());
jgen.writeString(value.getMatriculation());
jgen.writeString(value.getNom());
jgen.writeString(value.getPrenom());
jgen.writeString(value.getCompte());
jgen.writeString(value.getMarche());
jgen.writeString(value.getChat());
jgen.writeString(value.getMail());
jgen.writeString(value.getPhone());
jgen.writeEndObject();
}
}
in my controller i use my class like that:
AgentCust ags ;
// i set values here .
ObjectMapper mapper = new ObjectMapper();
String json = "";
try {
json = mapper.writeValueAsString(ags);
} catch (Exception e) {
System.out.println(e);
}
but at the end i get that :
org.codehaus.jackson.JsonGenerationException: Can not write number, expecting field name
any help please.
Why are you using a custom serializer(which is wrong as it doesn't include the field names). You are really complicating your life.
You can set the serialization options like this (you can also set them in a static block):
final ObjectMapper mapper = new ObjectMapper();
/*
you can set them globally in a static block and reuse the mapper...
performance gain
*/
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
mapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false);
mapper.setSerializationInclusion(Include.NON_NULL);
The rest of the code is the same(just add a constructor in your AgentCust.class to avoid some mapping errors):
AgentCust ags = new AgentCust();
ags.setChat("chat1");
ags.setCompte("compte1");
ags.setMail("mail1");
ags.setMarche("marche1");
ags.setMatriculation("matriculation1");
ags.setNom("nom1");
ags.setPersonneID(123456L);
ags.setPhone("phone1");
ags.setPrenom("prenom1");
String json = "";
try {
json = mapper.writeValueAsString(ags);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(json);
Another strange thing is that you're serializing the pojo as String. Why not JsonNode or ObjectNode?
public static ObjectNode convObjToONode(Object o) {
StringWriter stringify = new StringWriter();
ObjectNode objToONode = null;
try {
mapper.writeValue(stringify, o);
objToONode = (ObjectNode) mapper.readTree(stringify.toString());
} catch (JsonMappingException e) {
Logger.error("ERROR MAPPING JSON from object!", e);
} catch (JsonGenerationException e) {
Logger.error("ERROR GENERATING JSON from object!", e);
} catch (IOException e) {
Logger.error("ERROR IO when writing JSON from object!", e);
}
Logger.debug("Object as ObjectNode : " + objToONode);
return objToONode;
}

How can I deseralize json object in java pojo class?

I have a simple JSON statement which type is very per need. like this
{
actor:{name:"kumar",mbox:"kumar#gmail.com"}
verb :"completed"
}
or
{
actor:{name:["kumar","manish"],mbox:["kumar#gmail.com","manish#gmail.com"]}
verb :{
"id" : "http://adlnet.gov/expapi/verbs/completed",
"display" : {
"en-US" : "completed"
}
}
I am using using POJO class to map this json string and pojo class code is given bleow
#JsonProperty("actor")
Actor actor;
#JsonProperty("verb")
Verb objVerb;
#JsonProperty("verb")
String verb;
public Actor getActor() {
return actor;
}
public void setActor(Actor actor) {
this.actor = actor;
}
public Verb getObjVerb() {
return objVerb;
}
public void setObjVerb(Verb objVerb) {
this.objVerb = objVerb;
}
#JsonIgnore
public String getVerb() {
return verb;
}
#JsonIgnore
public void setVerb(String verb) {
this.verb = verb;
}
public static class Actor {
String objectType;
#JsonProperty("name")
ArrayList<String> listName;
#JsonProperty("name")
String name;
#JsonProperty("mbox")
ArrayList<String> listMbox;
#JsonProperty("mbox")
String mbox;
#JsonProperty("mbox_sha1sum")
ArrayList<String> Listmbox_sha1sum;
#JsonProperty("mbox_sha1sum")
String mbox_sha1sum;
#JsonProperty("openid")
String openid;
#JsonProperty("account")
Account account;
public String getObjectType() {
return objectType;
}
public void setObjectType(String objectType) {
this.objectType = objectType;
}
public ArrayList<String> getListName() {
return listName;
}
public void setListName(ArrayList<String> listName) {
this.listName = listName;
}
#JsonIgnore
public String getName() {
return name;
}
#JsonIgnore
public void setName(String name) {
this.name = name;
}
public ArrayList<String> getListMbox() {
return listMbox;
}
public void setListMbox(ArrayList<String> listMbox) {
this.listMbox = listMbox;
}
#JsonIgnore
public String getMbox() {
return mbox;
}
#JsonIgnore
public void setMbox(String mbox) {
this.mbox = mbox;
}
public ArrayList<String> getListmbox_sha1sum() {
return Listmbox_sha1sum;
}
public void setListmbox_sha1sum(ArrayList<String> listmbox_sha1sum) {
Listmbox_sha1sum = listmbox_sha1sum;
}
#JsonIgnore
public String getMbox_sha1sum() {
return mbox_sha1sum;
}
#JsonIgnore
public void setMbox_sha1sum(String mbox_sha1sum) {
this.mbox_sha1sum = mbox_sha1sum;
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public static class Account {
#JsonProperty("homePage")
String homePage;
#JsonProperty("name")
String name;
public String getHomePage() {
return homePage;
}
public void setHomePage(String homePage) {
this.homePage = homePage;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
public static class Verb {
String id;
Map<String,String> display;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Map<String, String> getDisplay() {
return display;
}
public void setDisplay(Map<String, String> display) {
this.display = display;
}
}
I am using jaxb and jakson. I am implementing the webservice to handle the json statement
so I use the bean class to map with json. But when I use to map this json then it gives the following exceptions
org.codehaus.jackson.map.JsonMappingException : property with the name "mbox" have two entry.
Define a proper bean structure so it directly mapped to the beans class
Try to leave only #JsonProperty("mbox") ArrayList<String> listMbox; field (don't need #JsonProperty("mbox")
String mbox;)
and add Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY=true to Jackson object mapper config.
So in deserialization it will be able to get as both array and single element.
you can use gson.
class cls = gson.fromJson(jsonString, clazz);
here jsonString can be stringified java script object. gson.fromJson method can map your java script key to java property.