How to encode input values in json using java - java

I have some input values like this:
customername
phone
email
.....
some items values
itemname1
itemname2
........
In every item name have some unitprice
quantity
........
I'm trying to encode these values in json like this:
{
"info": {
"customername": "abc",
"phone": "123",
"email": "an#gmail.com",
},
"item": {
"itemname1": {
"unitprice": "100",
"qty": "3",
},
"itemname2": {
"unitprice": "500",
"qty": "2",
}
}
}
I 'm unable to encode all value like above.
here is my code:
private void jsonEncoding() throws JSONException {
JSONObject obj = new JSONObject();
JSONObject obj1 = new JSONObject();
JSONObject obj2 = new JSONObject();
try {
obj1.put("name", name);
obj1.put("email", email);
obj1.put("phone", phone);
} catch (JSONException e) {
e.printStackTrace();
}
obj.put("info",obj1 );
System.out.print(obj);
System.out.print(obj1);
}
How to encode values like above json format.

You can do it in 2 ways:
Using 3rd party libraries like Gson/Jackson for converting the POJO class data to json object string (use http://www.jsonschema2pojo.org/ for creating POJO class easily)
Manually do JsonParsing like below:
try {
// info node
JSONObject objInfo = new JSONObject();
objInfo.put("name", name);
objInfo.put("email", email);
objInfo.put("phone", phone);
// itemname1 node
JSONObject itemname1 = new JSONObject();
itemname1.put("unitprice", unitprice1);
itemname1.put("qty", qty1);
// itemname2 node
JSONObject itemname2 = new JSONObject();
itemname2.put("unitprice", unitprice2);
itemname2.put("qty", qty2);
// item node
JSONObject item = new JSONObject();
// adding itemname1 & itemname2 to item
item.put("itemname1",itemname1);
item.put("itemname2",itemname2);
// root node
JSONObject root = new JSONObject();
root.put("info",objInfo);
root.put("item",item);
System.out.print(root);
} catch(JsonException e){
e.printStackTrace();
}

Create a POJO class similar to your response
class Info {
String customerName;
String phone;
String email;
}
class ItemName{
String unitprice;
String qty;
}
class Item{
ItemName itemname1;
ItemName itemname2;
}
class Data{
Info info;
Item item;
}
Now just use google gson library to convert instance of Data to json as in
new Gson().toJson(data);

Try this it may help
You need to create three classes and as your using Gson means you are going with networking feature hence implement serializable for all like below.
class CustomObject implements Serializable {
Info info;
Map<String, ItemName> item;
public CustomObject() {
this(null, null);
}
public CustomObject(Info info, Map<String, ItemName> item) {
this.info = info;
this.item = item;
}
public Info getInfo() {
return info;
}
public void setInfo(Info info) {
this.info = info;
}
public Map<String, ItemName> getItem() {
return item;
}
public void setItem(Map<String, ItemName> item) {
this.item = item;
}
}
class Info implements Serializable {
String customername;
String phone;
String email;
public Info() {
this("","","");
}
public Info(String customername, String phone, String email) {
this.customername = customername;
this.phone = phone;
this.email = email;
}
public String getCustomername() {
return customername;
}
public void setCustomername(String customername) {
this.customername = customername;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
class ItemName implements Serializable {
String unitprice;
String qty;
public ItemName() {
this("", "");
}
public ItemName(String unitprice, String qty) {
this.unitprice = unitprice;
this.qty = qty;
}
public String getUnitprice() {
return unitprice;
}
public void setUnitprice(String unitprice) {
this.unitprice = unitprice;
}
public String getQty() {
return qty;
}
public void setQty(String qty) {
this.qty = qty;
}
}
Now You Have to add your data as per need like below.
CustomObject customObject = new CustomObject();
Info info = new Info();
info.setCustomername("abc");
info.setPhone("123");
info.setEmail("an#gmail.com");
customObject.setInfo(info);
ItemName itemname1 = new ItemName();
itemname1.setUnitprice("100");
itemname1.setQty("3");
ItemName itemname2 = new ItemName();
itemname2.setUnitprice("500");
itemname2.setQty("2");
Map<String, ItemName> item = new HashMap<>();
item.put("itemname1", itemname1);
item.put("itemname2", itemname2);
customObject.setItem(item);
System.out.println(new Gson().toJson(customObject));
Above System.out.println gives output as
{
"info":
{
"customername":"abc",
"phone":"123",
"email":"an#gmail.com"},
"item":{
"itemname1":
{
"unitprice":"100",
"qty":"3"
},
"itemname2":
{
"unitprice":"500",
"qty":"2"
}
}
}
Now how to parse your string which you got from server or any source to that CustomObject class. Its very simple through Gson library by google.
String str = "{\n" +
" \"info\":\n" +
" {\n" +
" \"customername\":\"abc\",\n" +
" \"phone\":\"123\",\n" +
" \"email\":\"an#gmail.com\"\n" +
" },\n" +
" \"item\": \n" +
" {\n" +
" \"itemname1\":\n" +
" {\n" +
" \"unitprice\":\"100\",\n" +
" \"qty\":\"3\"\n" +
" },\n" +
" \"itemname2\":\n" +
" {\n" +
" \"unitprice\":\"500\",\n" +
" \"qty\":\"2\"\n" +
" }\n" +
" }\n" +
" }";
CustomObject customObject = new Gson().fromJson(str, new TypeToken<CustomObject>(){}.getType());
System.out.println(new Gson().toJson(customObject));

Related

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! :)

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);

Jackson data-bind deserialization: Skip over an element dependent on a value

I am using jackson library for deserializing json data.
Is there a way to skip some element if a attribute does not fit a criteria?
For Example
The java classes:
#JsonIgnoreProperties(ignoreUnknown = true)
public class Group
{
private String name;
private int id;
private List<User> userList;
}
#JsonIgnoreProperties(ignoreUnknown = true)
public class User
{
private String firstName;
private String lastName;
private boolean deleted;
}
The Json File:
["test.Group", {
"name" : "testgroup1",
"id" : 3
"userList" : [ "java.util.ArrayList", [
["test.User", {
"firstName" : "John",
"lastName" : "Doe",
"deleted" : false } ],
["test.User", {
"firstName" : "John",
"lastName" : "Doe",
"deleted" : true } ],
["test.User", {
"firstName" : "John",
"lastName" : "Doe",
"deleted" : false } ] ] ]
}]
Usually I am deserialzing like this:
ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
test.Group g1 = mapper.readValue(jsonString,test.Group.class);
Now, Is it possible to skip every user-element whose attribute "deleted" has value true ?
I there a way to do this with data-bind or do I have to use another method like tree or streaming ?
EDIT
I am developing for android, not desktop.
The reason for this question is, that there can be thousands of User elements and I want to minimize the memory usage.
Not skipping, but removing after reading using Java 8 (assuming your User has a getter for deleted):
g1.getUserList().removeIf(User::isDeleted);
You can inject an intermediary by parsing to a tree node and then filtering on the nodes. An example:
public static void main(String[] args)
{
Group g = new Group();
g.setId(1);
g.setName("Test");
User u1 = new User();
u1.setDeleted(false);
u1.setFirstName("John");
u1.setLastName("Jones");
User u2 = new User();
u2.setDeleted(true);
u2.setFirstName("Jane");
u2.setLastName("Jones");
g.addUser(u1);
g.addUser(u2);
try
{
ObjectMapper mapper = new ObjectMapper();
String jsonVal = mapper.writeValueAsString(g);
JsonNode node = mapper.readTree(jsonVal);
for (Iterator<Entry<String, JsonNode>> it = node.fields(); it.hasNext(); )
{
Map.Entry<String, JsonNode> field = it.next();
String key = field.getKey();
if ("userList".equals(key))
{
JsonNode users = field.getValue();
if (users.isArray())
{
for (Iterator<JsonNode> x = users.iterator(); x.hasNext();)
{
JsonNode entry = x.next();
if (entry.get("deleted").asBoolean())
{
System.out.println("Remove " + entry.get("firstName").asText() + " " + entry.get("lastName").asText());
x.remove();
}
else
{
System.out.println("Don't remove " + entry.get("firstName").asText() + " " + entry.get("lastName").asText());
}
}
}
}
}
Group grp = mapper.treeToValue(node, Group.class);
System.out.println("Final group: " + grp);
}
catch (Exception e)
{
System.out.println("Something went wrong...");
e.printStackTrace();
}
}
Output results in :
Don't remove John Jones
Remove Jane Jones
Final group: Group [name=Test, id=1, userList=[User [firstName=John, lastName=Jones, deleted=false]]]
Here is a second approach using a custom deserializer on the Group object. This is just something I read up on so there may be efficiencies that can be added:
public class Answer28536024 {
#JsonDeserialize(using = GroupDeserializer.class)
public static class Group
{
private String name;
private int id;
private List<User> userList;
public Group()
{
userList = new ArrayList<User>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void addUser(User u)
{
userList.add(u);
}
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
#Override
public String toString() {
return "Group [name=" + name + ", id=" + id + ", userList=" + userList
+ "]";
}
}
public static class GroupDeserializer extends JsonDeserializer<Group>
{
#Override
public Group deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
JsonNode node = jp.getCodec().readTree(jp);
Group group = new Group();
group.setName(node.get("name").asText());
group.setId(node.get("id").asInt());
JsonNode users = node.get("userList");
if (users.isArray())
{
for (JsonNode userNode : users)
{
if (!userNode.get("deleted").asBoolean())
{
User user = new User();
user.setFirstName(userNode.get("firstName").asText());
user.setLastName(userNode.get("lastName").asText());
user.setDeleted(false);
group.addUser(user);
}
}
}
return group;
}
}
public static class User
{
private String firstName;
private String lastName;
private boolean deleted;
public User()
{
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
#Override
public String toString() {
return "User [firstName=" + firstName + ", lastName=" + lastName
+ ", deleted=" + deleted + "]";
}
}
public static void main(String[] args)
{
Group g = new Group();
g.setId(1);
g.setName("Test");
User u1 = new User();
u1.setDeleted(false);
u1.setFirstName("John");
u1.setLastName("Jones");
User u2 = new User();
u2.setDeleted(true);
u2.setFirstName("Jane");
u2.setLastName("Jones");
g.addUser(u1);
g.addUser(u2);
try
{
ObjectMapper mapper = new ObjectMapper();
String jsonVal = mapper.writeValueAsString(g);
System.out.println(jsonVal);
Group grp = mapper.readValue(jsonVal, Group.class);
System.out.println("Final group: " + grp);
}
catch (Exception e)
{
System.out.println("Something went wrong...");
e.printStackTrace();
}
}
}
Output for this one:
{"name":"Test","id":1,"userList":[{"firstName":"John","lastName":"Jones","deleted":false},{"firstName":"Jane","lastName":"Jones","deleted":true}]}
Final group: Group [name=Test, id=1, userList=[User [firstName=John, lastName=Jones, deleted=false]]]

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());
}

How to parse a JSON string to an array using Jackson

I have a String with the following value:
[
{
"key1": "value11",
"key2": "value12"
},
{
"key1": "value21",
"key2": "value22"
}
]
And the following class:
public class SomeClass {
private String key1;
private String key2;
/* ... getters and setters omitted ...*/
}
And I want to parse it to a List<SomeClass> or a SomeClass[]
Which is the simplest way to do it using Jackson ObjectMapper?
I finally got it:
ObjectMapper objectMapper = new ObjectMapper();
TypeFactory typeFactory = objectMapper.getTypeFactory();
List<SomeClass> someClassList = objectMapper.readValue(jsonString, typeFactory.constructCollectionType(List.class, SomeClass.class));
The other answer is correct, but for completeness, here are other ways:
List<SomeClass> list = mapper.readValue(jsonString, new TypeReference<List<SomeClass>>() { });
SomeClass[] array = mapper.readValue(jsonString, SomeClass[].class);
The complete example with an array.
Replace "constructArrayType()" by "constructCollectionType()" or any other type you need.
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
public class Sorting {
private String property;
private String direction;
public Sorting() {
}
public Sorting(String property, String direction) {
this.property = property;
this.direction = direction;
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
public static void main(String[] args) throws JsonParseException, IOException {
final String json = "[{\"property\":\"title1\", \"direction\":\"ASC\"}, {\"property\":\"title2\", \"direction\":\"DESC\"}]";
ObjectMapper mapper = new ObjectMapper();
Sorting[] sortings = mapper.readValue(json, TypeFactory.defaultInstance().constructArrayType(Sorting.class));
System.out.println(sortings);
}
}
I sorted this problem by verifying the json on JSONLint.com and then using Jackson. Below is the code for the same.
Main Class:-
String jsonStr = "[{\r\n" + " \"name\": \"John\",\r\n" + " \"city\": \"Berlin\",\r\n"
+ " \"cars\": [\r\n" + " \"FIAT\",\r\n" + " \"Toyata\"\r\n"
+ " ],\r\n" + " \"job\": \"Teacher\"\r\n" + " },\r\n" + " {\r\n"
+ " \"name\": \"Mark\",\r\n" + " \"city\": \"Oslo\",\r\n" + " \"cars\": [\r\n"
+ " \"VW\",\r\n" + " \"Toyata\"\r\n" + " ],\r\n"
+ " \"job\": \"Doctor\"\r\n" + " }\r\n" + "]";
ObjectMapper mapper = new ObjectMapper();
MyPojo jsonObj[] = mapper.readValue(jsonStr, MyPojo[].class);
for (MyPojo itr : jsonObj) {
System.out.println("Val of getName is: " + itr.getName());
System.out.println("Val of getCity is: " + itr.getCity());
System.out.println("Val of getJob is: " + itr.getJob());
System.out.println("Val of getCars is: " + itr.getCars() + "\n");
}
POJO:
public class MyPojo {
private List<String> cars = new ArrayList<String>();
private String name;
private String job;
private String city;
public List<String> getCars() {
return cars;
}
public void setCars(List<String> cars) {
this.cars = cars;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
} }
RESULT:-
Val of getName is: John
Val of getCity is: Berlin
Val of getJob is: Teacher
Val of getCars is: [FIAT, Toyata]
Val of getName is: Mark
Val of getCity is: Oslo
Val of getJob is: Doctor
Val of getCars is: [VW, Toyata]

Categories