jackson java Unrecognized field not marked as ignorable - java

The error code :
org.codehaus.jackson.map.exc.UnrecognizedPropertyException:
Unrecognized field "id" (Class JacksonTester$Student), not
marked as ignorable
at [Source: [B#40334c25; line: 2, column: 8]
(through reference chain: Student["id"])
I have the below JSON file:
{
"id": "0",
"title": "0",
"externalId": "0",
"externalLink": "0",
"sourceApplication": "0",
"content": "0",
"summaryContent": "0",
"publishedDate": "0",
"harvestDate": "0",
"languageId": "0",
"regionId": "0",
"postStatus": "0"
}
and my code is
JacksonTester.java:
public class JacksonTester {
public static void main(String args[]) {
ObjectMapper mapper = new ObjectMapper();
// map json to student
try {
byte[] jsonData = Files.readAllBytes(Paths.get("output_json.txt"));
Student student = mapper.readValue(jsonData, Student.class);
System.out.println(student);
} catch (Exception e) {
e.printStackTrace();
}
}
static class Student {
String id;
String title;
String externalId;
String externalLink;
String sourceApplication;
String content;
String summaryContent;
String publishedDate;
String harvestDate;
String languageId;
String regionId;
String postStatus;
public Student() {
}
}
}

You need to either have setters for those fields or a constructor that accepts those fields as parameters (+ approriate annotations or -parameters from Java 8 and jackson-module-parameter-names
module):
public static class Student {
...
String postStatus;
public setPostStatus(postStatus) {
this.postStatus = postStatus;
}
...
}

Jackson has no access to the fields of Student.
Implement the public getters and setters for Student and it works.

I sorted this problem and it's working fine. Here is my code for the same.
**MainClass.java:**
public class MainClass {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
String jsonStr = "{\r\n" + " \"id\": \"168\",\r\n" + " \"title\": \"Mr\",\r\n"
+ " \"externalId\": \"247518\",\r\n" + " \"externalLink\": \"www.gmail.com\",\r\n"
+ " \"sourceApplication\": \"adsense\",\r\n" + " \"content\": \"hmtl\",\r\n"
+ " \"summaryContent\": \"null\",\r\n" + " \"publishedDate\": \"12122018\",\r\n"
+ " \"harvestDate\": \"12122018\",\r\n" + " \"languageId\": \"3\",\r\n" + " \"regionId\": \"45\",\r\n"
+ " \"postStatus\": \"1\"\r\n" + "}";
ObjectMapper mapper = new ObjectMapper();
MyPojo details = mapper.readValue(jsonStr, MyPojo.class);
System.out.println("Value for getId is: " + details.getId());
System.out.println("Value for getSourceApplication is: " + details.getSourceApplication());
System.out.println("Value for getExternalId is: " + details.getPublishedDate());
System.out.println("Value for getExternalLink is: " + details.getExternalLink());
} }
**MyPojo.class**
public class MyPojo {
private String content;
private String id;
private String sourceApplication;
private String title;
private String postStatus;
private String publishedDate;
private String summaryContent;
private String harvestDate;
private String languageId;
private String externalId;
private String regionId;
private String externalLink;
public String getContent() {
return content;
}
public String getId() {
return id;
}
public String getSourceApplication() {
return sourceApplication;
}
public String getTitle() {
return title;
}
public String getPostStatus() {
return postStatus;
}
public String getPublishedDate() {
return publishedDate;
}
public String getSummaryContent() {
return summaryContent;
}
public String getHarvestDate() {
return harvestDate;
}
public String getLanguageId() {
return languageId;
}
public String getExternalId() {
return externalId;
}
public String getRegionId() {
return regionId;
}
public String getExternalLink() {
return externalLink;
} }
**RESULT:**
Value for getId is: 168
Value for getSourceApplication is: adsense
Value for getExternalId is: 12122018
Value for getExternalLink is: www.gmail.com
NOTE
One has to change the fields in the json to begin with a lower case letter. The reason for the JSON change is that the Jackson bean serialisation will reflect over the class, and when it sees getXyz() and setXyz() methods will map these to a Json filed names "xyz" (and not "Xyz").I think there are several ways to override this behaviour, one is to use the one of the Jackson annotations.

Instead of creating so many public getters, you could simply modify private variables to public

Related

Error com.fasterxml.jackson.core.JsonParseException: Unrecognized token

Trying to read a JSON file and serialize it to java object, I wrote a method:
public static PostPojo readFile(String titleFile){
String pathJSONFile = "src/main/resources/"+titleFile+".json";
ObjectMapper objectMapper = new ObjectMapper();
try {
objectMapper.readValue(pathJSONFile,PostPojo.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return postPojo;
}
but it produces an error:
com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'src': was expecting (JSON
String, Number, Array, Object or token 'null', 'true' or 'false')
at [Source: (String)"src/main/resources/ninetyNinthPost.json"; line: 1, column: 4]
at utils.ApiUtils.readFile(ApiUtils.java:71)
at ApiApplicationRequest.getValue(ApiApplicationRequest.java:31)
My JSON file from which values are calculated
[ {
"userId" : 10,
"id" : 99,
"title" : "temporibus sit alias delectus eligendi possimus magni",
"body" : "quo deleniti praesentium dicta non quod\naut est
molestias\nmolestias et officia quis nihil\nitaque dolorem quia"
} ]
My java object class
public class PostPojo {
private int userId;
private int id;
private String title;
private String body;
public PostPojo() {
}
public PostPojo(int userId, int id, String title, String body) {
this.userId = userId;
this.id = id;
this.title = title;
this.body = body;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
#Override
public String toString() {
return "PostModel{" +
"userId=" + userId +
", id=" + id +
", title='" + title + '\'' +
", body='" + body + '\'' +
'}';
}
}
I really don't understand what is the reason.As I understand it, reading in the documentation, it should read the file and present it in the java class. Any sugestions?
There is no method signature supposed to get a file path as first argument. You may pass a JSON String as first argument or you could use the method signature with a File Object as first argument, like this:
public static PostPojo[] readFile(String titleFile){
String pathJSONFile = "src/main/resources/"+titleFile+".json";
ObjectMapper objectMapper = new ObjectMapper();
File jsonFile = new File(pathJSONFile);
PostPojo[] postPojo = null;
try {
postPojo = objectMapper.readValue(jsonFile, PostPojo[].class);
} catch (IOException e) {
e.printStackTrace();
}
return postPojo;
}
EDIT: Since your file defines a wrapping array around the object you have to parse it as array. Afterwards you may return it as an array like i did in my edited answer or you just return the first array record.

How tor retrieve String array from JSON Array?

I have an Android App (written in Java) which retrieves a JSON object from the backend, parses it, and displays the data in the app. Everything is working fine (meaning that every field is being displayed correctly) except for one field. All the fields being displayed correctly are String whereas the one field which is causing the error is a string array!
Sample Object being retried from backend:
{
"attendance_type": "2",
"guest": [
"Test Guest",
"Test Guest 2"
],
"member_id": "1770428",
"attendance_time": "2020-04-27 04:42:22",
"name": "HENRY HHH",
"last_name": "",
"email": "henry#mailinator.com",
"onesignal_playerid": "",
"user_image": "311591.png",
"dateOfBirth": "06/22/1997",
"employeeID": "543210",
"socialSecurityNumber": "0000"
}
As I said, all the fields are being retrieved correctly except the "guest field"
This is the class in which everything is Serialized:
package com.lu.scanner.ui.attendance.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class AttendanceDetails {
String date;
#SerializedName("attendance_type")
private String attendance_type;
#SerializedName("member_id")
private String member_id;
#SerializedName("attendance_date")
private String attendance_date;
#SerializedName("name")
private String name;
#SerializedName("email")
private String email;
#SerializedName("onesignal_playerid")
private String onesignal_playerid;
#SerializedName("user_image")
private String user_image;
#SerializedName("dateOfBirth")
private String dateOfBirth;
#SerializedName("employeeID")
private String employeeID;
#SerializedName("socialSecurityNumber")
private String socialSecurityNumber;
#SerializedName("attendance_time")
private String attendance_time;
#SerializedName("guest")
private String[] guest;
public AttendanceDetails(String date) {
this.date = date;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAttendance_type() {
return attendance_type;
}
public void setAttendance_type(String attendance_type) {
this.attendance_type = attendance_type;
}
public String getMember_id() {
return member_id;
}
public void setMember_id(String member_id) {
this.member_id = member_id;
}
public String getAttendance_date() {
return attendance_date;
}
public void setAttendance_date(String attendance_date) {
this.attendance_date = attendance_date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getOnesignal_playerid() {
return onesignal_playerid;
}
public void setOnesignal_playerid(String onesignal_playerid) {
this.onesignal_playerid = onesignal_playerid;
}
public String getUser_image() {
return user_image;
}
public void setUser_image(String user_image) {
this.user_image = user_image;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getEmployeeID() {
return employeeID;
}
public void setEmployeeID(String employeeID) {
this.employeeID = employeeID;
}
public String getSocialSecurityNumber() {
return socialSecurityNumber;
}
public void setSocialSecurityNumber(String socialSecurityNumber) {
this.socialSecurityNumber = socialSecurityNumber;
}
public String getAttendance_time() {
return attendance_time;
}
public void setAttendance_time(String attendance_time) {
this.attendance_time = attendance_time;
}
public String[] getGuest(){
return guest;
}
public void setGuest(String[] guest){
this.guest=guest;
}
}
This is the SQLLite database:
private static final String CREATE_TABLE_ATTENDANCE_DETAILS = "CREATE TABLE IF NOT EXISTS " + TABLE_ATTENDANCE_DETAILS +
"( date TEXT , " +
"attendance_type TEXT, " +
"member_id TEXT, " +
"attendance_date TEXT, " +
"name TEXT, " +
"email TEXT, " +
"onesignal_playerid TEXT, " +
"user_image TEXT, " +
"dateOfBirth TEXT, " +
"employeeID TEXT, " +
"socialSecurityNumber TEXT, " +
"attendance_time TEXT, " +
"guest TEXT); ";
And finally, there is where the data is being retrieved:
public List<AttendanceDetails> getAllAttendanceDetails() {
List<AttendanceDetails> attendanceDetailsList = new ArrayList<AttendanceDetails>();
String selectQuery = "SELECT * FROM " + TABLE_ATTENDANCE_DETAILS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
AttendanceDetails attendanceDetails = new AttendanceDetails();
attendanceDetails.setDate(cursor.getString(0));
attendanceDetails.setAttendance_type(cursor.getString(1));
attendanceDetails.setMember_id(cursor.getString(2));
attendanceDetails.setAttendance_date(cursor.getString(3));
attendanceDetails.setName(cursor.getString(4));
attendanceDetails.setEmail(cursor.getString(5));
attendanceDetails.setOnesignal_playerid(cursor.getString(6));
attendanceDetails.setUser_image(cursor.getString(7));
attendanceDetails.setDateOfBirth(cursor.getString(8));
attendanceDetails.setEmployeeID(cursor.getString(9));
attendanceDetails.setSocialSecurityNumber(cursor.getString(10));
attendanceDetails.setAttendance_time(cursor.getString(11));
attendanceDetails.setGuest(cursor.getString(12));
attendanceDetailsList.add(attendanceDetails);
} while (cursor.moveToNext());
}
return attendanceDetailsList;
}
Therefore, the main problem, I think, is that the TEXT type in the table creation is not compatible with the String array. Plus I think the cursor.String() function is not working for the "guest" string array properly. What can I do to make all of this code compatible with the "guest" field?
NOTE: Everything is working perfectly fine except for the guest field...
A Database stores rows of data, divided into columns. Each column is a skalar. SQLite only supports (basically) numbers and Text for columns. A List of Texts (or array from strings) doesn't fit in there. You are trying to assign a single String to an array.
You have two options:
Model guest as its own table and use foreign keys and the appropriate JOIN to fetch the data.
Encode the data yourself. If you don't want to query the array, but always retrieve the whole thing, this is the easier way:
Gson gson;
String guestSerialized = gson.toJson(attendanceDetails.getGuest);
// Insert data like this
// Retrieve:
attendanceDetails.setGuest(gson.fromJson(cursor.getString(12), String[].class))
That is, if you are using GSON for JSON (de)serialization. You can choose a different format or library.
Maybe you could give some name in the fields of "guest", something like:
"guest": [
{
"guest" : "Test Guest",
},
{
"guest" : "Test Guest 2"
},
],
Then, in order to read these values, you can do that:
JSONArray ja = (JSONArray) jo.get("guest");
Map address = ((Map)jo.get("guest"))
Iterator itr = ja.iterator();
Iterator<Map.Entry> itr1;
while (itr.hasNext()) {
itr1 = ((Map) itr.next()).entrySet().iterator();
while (itr1.hasNext()) {
Map.Entry pair = itr1.next();
System.out.println(pair.getKey() + " : " + pair.getValue());
}
}
Where:
pair.getKey is the name of the key ("guest")
pair.getValue is the value of the key ("Test Guest")
The source code is here.
Sorry if I have made any mistakes. Please ask for clarifications! :)

Getting multiple properties from multiple objects in JSON list through GSON

I have a json that contains 3 objects: question, tags, and choices.
[
{
"question" : {
"questionId" : 01,
"isActive" : 1
},
"tags" : ["tag1", "tag2"],
"choices" : [{
"choiceId" : 0,
"questionId" : 0
}, {
"choiceId" : 1,
"questionId" : 0
}
]
}
]
I currently am using GSON and this Extractor class with the intention of getting the details from the 3 different objects:
public class Extractor {
//question, tags, and choices are existing classes
Questions question;
List<Tags> tags;
List<Choice> choices;
//getters and setters
}
Extractor result = gson.fromJson(jsonString, Extractor.class);
//I want to see the question, tag, and choice parts from the json
System.out.println("Result" + result.getTags().get(0).getName() + result.getChoices().get(0).getChoiceId());
What am I doing wrong? How do I get the properties of question, tags, and choices separately? Also, how would I be able to iterate over a JSONlist that contains multiple questions, tags, and choices?
The below code should get the question, tags and choices separately as long as the POJO classes are defined correctly. Please refer this similar post for POJO class definitions.
public static void main(String[] args) {
String jsonString = "[{\"question\":{\"questionId\":01,\"isActive\":1},\"tags\":[\"tag1\",\"tag2\"],\"choices\":[{\"choiceId\":0,\"questionId\":0},{\"choiceId\":1,\"questionId\":0}]}]";
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(jsonString).getAsJsonArray();
for (final JsonElement json : array) {
Extracter jsonModel = gson.fromJson(json, new TypeToken<Extracter>() {
}.getType());
System.out.println(jsonModel.toString());
List<Choices> choicesList = jsonModel.getChoices();
//Looping the choices
for (Choices choice :choicesList) {
System.out.println("Choice :" + choice);
System.out.println("Choice Id :" + choice.getChoiceId());
System.out.println("Question Id :" + choice.getQuestionId());
}
//Printing the question
System.out.println("Question obj data :" + jsonModel.getQuestion());
System.out.println("Course Id :" + jsonModel.getQuestion().getQuestionId());
System.out.println("Active :" + jsonModel.getQuestion().getIsActive());
//Printing the tags
System.out.println(jsonModel.getTags());
}
}
Output:-
Choice :Choices [choiceId=0, questionId=0]
Choice Id :0
Question Id :0
Choice :Choices [choiceId=1, questionId=0]
Choice Id :1
Question Id :0
Question obj data :Question [questionId=1, courseId=null, isActive=1]
Course Id :1
Active :1
[tag1, tag2]
POJO Classes:-
public class Extracter implements Serializable {
private static final long serialVersionUID = -2255013835370141266L;
private List<Choices> choices;
private List<String> tags;
private Question question;
public List<Choices> getChoices() {
return choices;
}
public void setChoices(List<Choices> choices) {
this.choices = choices;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public Question getQuestion() {
return question;
}
public void setQuestion(Question question) {
this.question = question;
}
#Override
public String toString() {
return "JsonModel [choices=" + choices + ", tags=" + tags + ", question=" + question + "]";
}
}
public class Choices implements Serializable{
private static final long serialVersionUID = 3947337014862847527L;
private Integer choiceId;
private Integer questionId;
public Integer getChoiceId() {
return choiceId;
}
public void setChoiceId(Integer choiceId) {
this.choiceId = choiceId;
}
public Integer getQuestionId() {
return questionId;
}
public void setQuestionId(Integer questionId) {
this.questionId = questionId;
}
#Override
public String toString() {
return "Choices [choiceId=" + choiceId + ", questionId=" + questionId + "]";
}
}
public class Question implements Serializable{
private static final long serialVersionUID = -8649775972572186614L;
private Integer questionId;
private Integer courseId;
private Integer isActive;
public Integer getQuestionId() {
return questionId;
}
public void setQuestionId(Integer questionId) {
this.questionId = questionId;
}
public Integer getCourseId() {
return courseId;
}
public void setCourseId(Integer courseId) {
this.courseId = courseId;
}
public Integer getIsActive() {
return isActive;
}
public void setIsActive(Integer isActive) {
this.isActive = isActive;
}
#Override
public String toString() {
return "Question [questionId=" + questionId + ", courseId=" + courseId + ", isActive=" + isActive + "]";
}
}

How to convert JSON object from third party api into local POJO

Let's say i make a call to a thrid party API to get a object Task and I get the following JSON String in return:
{
"tasks": [
{
"id": 1,
"code": "CODE",
"description": "Dummy Task",
"withConfirmation": false,
"resource": {
"id": "abcdef12-fe14-57c4-acb5-1234e7456d62",
"group": "Doctor",
"firstname": "Toto",
"lastname": "Wallace",
},
{
"id": 2,
"code": "CODE",
"description": "Dummyyy Taaask",
"withConfirmation": false
}
]
}
In the returned json we have a Task which can be joined with a Resource.
In our system, a Task is as the following:
#JsonAutoDetect
public class Task implements Serializable {
private Integer id;
private String code = "BASIC";
private String description;
private boolean withConfirmation = false;
/**
* CONSTRUCTOR
*/
public Task() {
}
public Integer getId() {
return id;
}
#JsonProperty
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
#JsonProperty
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#JsonProperty
public boolean isWithConfirmation() {
return withConfirmation;
}
public void setWithConfirmation(boolean withConfirmation) {
this.withConfirmation = withConfirmation;
}
public String toString() {...
}
}
and a Resource looks like that:
public class Resource implements Serializable {
...
private String firstname;
private String lastname;
private MedicalGroup group; // id + name + description
private Set<Task> tasks = new HashSet<Task>(0);
...
// getters and setters and toString etc.
...
}
So the major difference, aside from the field names is that a Task does not contain any Resource but the relation is rather in the opposite direction which means that a Resource can hold n Task.
What would be for this case the best way to serialize the returned json object from the third party and convert/map it to a pojo from my own system?
I'm currently reading Gson doc in order to try it but any suggestion is welcomed.
This code has to be easily reusable cause it's going to be needed inside multiple projects.
It is not full working code, because i have no idea how you want to work with Resource. Should Json create new resource or try to find already existing one. How will you create MedicalGroup from json, because it is not enuogh data for that. I was going to ask this in comments, but there is not enough space. And here is demo how you can try to solve most of the problems except the Resources to/from json mapping.
Main idea is to add #JsonAnyGetter public Map<String, Object> getAdditionalProperties() and #JsonAnySetter public void setAdditionalProperty(String name, Resource value) in your Task POJO:
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
HashMap<String, Object> map= new HashMap<>();
// IMPORTANT
// here we can try to find resource that has this task
// and export its info to json like this:
// CHANGE THIS
Resource res = new Resource();
res.firstname = "Toto";
res.lastname = "Wallace";
// IMPORTANT END
map.put("resource", res);
return map;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Resource value) {
// IMPORTANT
// Here you have to create or find appropriate Resource in your code
// and add current task to it
System.out.println(name+" "+ value );
}
FULL Demo:
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;
public class Main3 {
private static String json = "{\n" +
" \"tasks\": [\n" +
" {\n" +
" \"id\": 1,\n" +
" \"code\": \"CODE\",\n" +
" \"description\": \"Dummy Task\",\n" +
" \"withConfirmation\": false,\n" +
" \"resource\": {\n" +
" \"id\": \"abcdef12-fe14-57c4-acb5-1234e7456d62\",\n" +
" \"group\": \"Doctor\",\n" +
" \"firstname\": \"Toto\",\n" +
" \"lastname\": \"Wallace\"\n" +
" }},\n" +
" {\n" +
" \"id\": 2,\n" +
" \"code\": \"CODE\",\n" +
" \"description\": \"Dummyyy Taaask\",\n" +
" \"withConfirmation\": false\n" +
" }\n" +
" ]\n" +
" }";
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
TasksList tl = mapper.readValue(json, TasksList.class);
String result = mapper.writeValueAsString(tl);
System.out.println(result);
}
private static class TasksList {
#JsonProperty(value = "tasks")
private List<Task> tasks;
}
#JsonIgnoreProperties(ignoreUnknown = true)
public static class Resource implements Serializable {
#JsonProperty(value = "firstname")
private String firstname;
#JsonProperty(value = "lastname")
private String lastname;
// HAVE NO IDEA HOW YOU GONNA MAP THIS TO JSON
// private MedicalGroup group; // id + name + description
private Set<Task> tasks = new HashSet<Task>(0);
#Override
public String toString() {
return "Resource{" +
"firstname='" + firstname + '\'' +
", lastname='" + lastname + '\'' +
", tasks=" + tasks +
'}';
}
}
#JsonAutoDetect
public static class Task implements Serializable {
private Integer id;
private String code = "BASIC";
private String description;
private boolean withConfirmation = false;
/**
* CONSTRUCTOR
*/
public Task() {
}
public Integer getId() {
return id;
}
#JsonProperty
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
#JsonProperty
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#JsonProperty
public boolean isWithConfirmation() {
return withConfirmation;
}
public void setWithConfirmation(boolean withConfirmation) {
this.withConfirmation = withConfirmation;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
HashMap<String, Object> map= new HashMap<>();
// IMPORTANT
// here we can try to find resource that has this task
// and export its info to json like this:
// CHANGE THIS
Resource res = new Resource();
res.firstname = "Toto";
res.lastname = "Wallace";
// IMPORTANT END
map.put("resource", res);
return map;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Resource value) {
// IMPORTANT
// Probably here you have to create or find appropriate Resource in your code
// and add current task to it
System.out.println(name+" "+ value );
}
#Override
public String toString() {
return "Task{" +
"id=" + id +
", code='" + code + '\'' +
", description='" + description + '\'' +
", withConfirmation=" + withConfirmation +
'}';
}
}
}
you can use Gson library by google to convert Json to Pojo Class.
new Gson().fromJson(jsonString,Response.class);

Converting Json to java objects using Google's Gson

I am using Spring Social FqlQuery to get data's from facebook. Here is the JSON response I am getting from facebook. My controller where i am getting Json output is here,
fql = "SELECT work FROM user WHERE uid = me()";
facebook.fqlOperations().query(fql, new FqlResultMapper<Object>() {
public Object mapObject(FqlResult result) {
List list = (List) result.getObject("work");
for (Object object : list) {
JsonHelper jsonHelper = new JsonHelper();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(object);
System.out.println(jsonOutput);
gson.fromJson(jsonOutput, JsonHelper.class);
}
System.out.println inside for loop Outputs multiple json as below.:
{
"employer": {
"id": 129843057436,
"name": "www.metroplots.com"
},
"location": {
"id": 102186159822587,
"name": "Chennai, Tamil Nadu"
},
"position": {
"id": 108480125843293,
"name": "Web Developer"
},
"start_date": "2012-10-01",
"end_date": "2013-05-31"
}
{
"employer": {
"id": 520808381292985,
"name": "Federation of Indian Blood Donor Organizations"
},
"start_date": "0000-00",
"end_date": "0000-00"
}
Here is my Helper Class:
import java.util.List;
public class JsonHelper {
class Employer{
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Location{
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Position{
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//Edited After here
private String start_Date;
private String end_Date;
private Employer employer;
private Location location;
private Position position;
public String getStart_Date() {
return start_Date;
}
public void setStart_Date(String start_Date) {
this.start_Date = start_Date;
}
public String getEnd_Date() {
return end_Date;
}
public void setEnd_Date(String end_Date) {
this.end_Date = end_Date;
}
public Employer getEmployer() {
return employer;
}
public void setEmployer(Employer employer) {
this.employer = employer;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public Position getPosition() {
return position;
}
public void setPosition(Position position) {
this.position = position;
}
}
When I try to convert the json objects to java object as done above I am getting this exception.
HTTP Status 500 - Request processing failed; nested exception is com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 6 column 16
Can any one help me where I am wrong. Please help me converting json to java objects. Hope my question is clear. Thanks in advance.
EDIT MADE TO CONTROLLER:
facebook.fqlOperations().query(fql, new FqlResultMapper<Object>() {
public Object mapObject(FqlResult result) {
List<JsonHelper> json = new ArrayList<JsonHelper>();
List list = (List) result.getObject("work");
for (Object object : list) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(object);
System.out.println(jsonOutput);
JsonHelper jsonHelper = gson.fromJson(jsonOutput, JsonHelper.class);
json.add(jsonHelper);
System.out.println(jsonHelper.getStart_Date());
}
for (JsonHelper jsonHelper : json) {
System.out.println(jsonHelper.getStart_Date());
}
return list;
}
});
Since i am not having the actual api access, so i am trying it with static value in the example. Firstly in your JsonHelper class, replace all int by long , as the values mentioned in the json are of type long and String. Then try it like mentioned below:
String str = "{\n"
+ " \"employer\": {\n"
+ " \"id\": 129843057436,\n"
+ " \"name\": \"www.metroplots.com\"\n"
+ " },\n"
+ " \"location\": {\n"
+ " \"id\": 102186159822587,\n"
+ " \"name\": \"Chennai, Tamil Nadu\"\n"
+ " },\n"
+ " \"position\": {\n"
+ " \"id\": 108480125843293,\n"
+ " \"name\": \"Web Developer\"\n"
+ " },\n"
+ " \"start_date\": \"2012-10-01\",\n"
+ " \"end_date\": \"2013-05-31\"\n"
+ "}";
List<JsonHelper> json = new ArrayList<JsonHelper>();
Gson gson = new Gson();
JsonHelper users = gson.fromJson(str, JsonHelper.class);
json.add(users);
for (JsonHelper js_obj : json) {
System.out.println(js_obj.getEmployer().getId());
System.out.println(js_obj.getEmployer().getName());
}

Categories