Well so I'm trying to parse a bit of JSon. I succeeded to parse:
Member.json:
{"member":{"id":585897,"name":"PhPeter","profileIconId":691,"age":99,"email":"peter#adress.com "}}
but what if I need to parse:
{"Members":[{"id":585897,"name":"PhPeter","profileIconId":691,"age":99,"email":"peter#adress.com"},{"id":645231,"name":"Bill","profileIconId":123,"age":56,"email":"bill#adress.com"}]}
Ofcourse I searched the web, I think, I need to use "List<>" here private List<memberProfile> member;but how do I "get" this from my main class??
I used this to parse the first string:
memeberClass.java
public class memberClass {
private memberProfile member;
public memberProfile getMember() {
return member;
}
public class memberProfile{
int id;
String name;
int profileIconId;
int age;
String email;
//Getter
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getProfileIconId() {
return profileIconId;
}
public int getAge() {
return age;
}
public String getEmail() {
return email;
}
}
}
memberToJava.java
public class memberToJava {
public static void main(String[] args) {
Gson gson = new Gson();
try {
BufferedReader br = new BufferedReader(new FileReader("...Member.json"));
//convert the json string back to object
memberClass memberObj = gson.fromJson(br, memberClass.class);
System.out.println("Id: " + memberObj.getMember().getId());
System.out.println("Namw: " + memberObj.getMember().getName());
System.out.println("ProfileIconId: " + memberObj.getMember().getProfileIconId());
System.out.println("Age: " + memberObj.getMember().getAge());
System.out.println("Email: " + memberObj.getMember().getEmail());
} catch (IOException e) {
e.printStackTrace();
}
}
}
see below code
MemberClass.java
import java.util.List;
public class MemberClass {
private List<MemberProfile> member;
public List<MemberProfile> getMember() {
return member;
}
public void setMember(List<MemberProfile> member) {
this.member = member;
}
public class MemberProfile {
int id;
String name;
int profileIconId;
int age;
String email;
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;
}
public int getProfileIconId() {
return profileIconId;
}
public void setProfileIconId(int profileIconId) {
this.profileIconId = profileIconId;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
}
Main Class
import com.google.gson.Gson;
public class MemTest {
public static void main(String[] args) {
String json = "{'member':[{'id':585897,'name':'PhPeter','profileIconId':691,'age':99,'email':'peter#adress.com'},{'id':645231,'name':'Bill','profileIconId':123,'age':56,'email':'bill#adress.com'}]}";
MemberClass memberClass = new Gson().fromJson(json, MemberClass.class);
System.out.println(new Gson().toJson(memberClass));
}
}
Output
{"member":[{"id":585897,"name":"PhPeter","profileIconId":691,"age":99,"email":"\u0027peter#adress.com\u0027"},{"id":645231,"name":"Bill","profileIconId":123,"age":56}]}
Hi I made some changes to your application and it seems to work now ! You where quite close alls you need is a wrapper for the array.
public class memberWrapper {
private List<memberClass> Members;
public List<memberClass> getMembers() {
return Members;
}
public void setMembers(List<memberClass> members) {
this.Members = members;
}
}
Then I changed youir original class a little:
public class memberClass {
int id;
String name;
int profileIconId;
int age;
String email;
//Getter
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getProfileIconId() {
return profileIconId;
}
public int getAge() {
return age;
}
public String getEmail() {
return email;
}
}
and then in the main:
BufferedReader br = new BufferedReader(new FileReader("stuff.json"));
//convert the json string back to object
memberWrapper memberObj = gson.fromJson(br, memberWrapper.class);
System.out.println("Id: " + memberObj.getMembers().get(0).getId());
It should work now the important thing when dealing with JSOn is to just make sure the key matches the name of your variables.
Related
This question already has answers here:
Sort ArrayList of custom Objects by property
(29 answers)
Closed 5 years ago.
I have status like "In consultation","Waiting in Queue". all the data coming from json API and add all that data into array list using Pojo class.then how to sort this array list by Consultation status.
Patient Class:
public class Patient_Get_Set implements Serializable {
private String fullName;
private String age;
private String waitTime;
private String sex;
private String patientID;
private String gender;
private String dateOfBirth;
private String phoneNo;
private String Diagnosis;
private String Email;
private String token_id;
private String priority;
private String consultation_status;
private String case_number;
public String getCase_number() {
return case_number;
}
public void setCase_number(String case_number) {
this.case_number = case_number;
}
public String getConsultation_status() {
return consultation_status;
}
public void setConsultation_status(String consultation_status) {
this.consultation_status = consultation_status;
}
public String getPriority() {
return priority;
}
public void setPriority(String priority) {
this.priority = priority;
}
public String getToken_id() {
return token_id;
}
public void setToken_id(String token_id) {
this.token_id = token_id;
}
public String getConsultationstatus() {
return consultationstatus;
}
public void setConsultationstatus(String consultationstatus) {
this.consultationstatus = consultationstatus;
}
private String consultationstatus;
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getVisitorType() {
return visitorType;
}
public void setVisitorType(String visitorType) {
this.visitorType = visitorType;
}
private String visitorType;
public String getDiagnosis() {
return Diagnosis;
}
public void setDiagnosis(String diagnosis) {
Diagnosis = diagnosis;
}
private String patientJsonArray;
public void setFullName(String fullName) {
this.fullName = fullName;
}
public void setAge(String age) {
this.age = age;
}
public void setWaitTime(String waitTime) {
this.waitTime = waitTime;
}
public String getFullName() {
return fullName;
}
public String getAge() {
return age;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getSex() {
return sex;
}
public String getWaitTime() {
return waitTime;
}
public void setPatientID(String patientID) {
this.patientID = patientID;
}
public void setGender(String gender) {
this.gender = gender;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public String getPhoneNo() {
return phoneNo;
}
public String getPatientID() {
return patientID;
}
public void setPatientJsonArray(String patientJsonArray) {
this.patientJsonArray = patientJsonArray;
}
public String getPatientJsonArray() {
return patientJsonArray;
}
public String getGender() {
return gender;
}
}
Here is code what you can use for your custom need -
Collections.sort(list, new Comparator<Patient_Get_Set>() {
#Override
public int compare(final Patient_Get_Set object1, final Patient_Get_Set object2) {
List<String> statusList = new ArrayList();
statusList.add("consultation");statusList.add("queue"); statusList.add("waiting");
return new Integer(statusList.indexOf(object1.getConsultation_status())).compareTo(new Integer(statusList.indexOf(object2.getConsultation_status())));
}
});
add elements in statusList in same order in which order you want pojo class to be sorted.
You can use Collections to sort your array list objects.
for example your list as below.
ArrayList<Patient> list = new ArrayList<Patient>();
Then you can sort list using below code.
Collections.sort(list, new Comparator<Patient>() {
#Override
public int compare(final Patient object1, final Patient object2) {
return object1.getConsultation_status().compareTo(object2.getConsultation_status());
}
});
OR
If you are using Java version 1.8 then you can sort list using below code.
list.stream()
.sorted((object1, object2) -> object1.getConsultation_status().compareTo(object2.getConsultation_status()));
import static java.util.Comparator.comparing;
Collections.sort(list, comparing(MyObject::getStartDate));
compare data with comparing in java8 follow http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html
I am trying to get some the array of actors from Jira. The code for the wrapper is used in a Gson.fromJson call. I had used something similar with a json string that did not have an array in it that had the information I needed and it worked fine, so the issue seems to do with the array, but I am not 100% sure:
import com.google.gson.annotations.SerializedName;
public class JiraRoleJsonWrapper {
#SerializedName("self")
private String self;
#SerializedName("name")
private String name;
#SerializedName("id")
private int id;
#SerializedName("description")
private String description;
#SerializedName("actors")
private JiraActors[] actors;
public JiraActors[] getActors() {
return actors;
}
public void setActors(JiraActors[] actors) {
this.actors = actors;
}
public String getSelf() {
return self;
}
public void setSelf(String self) {
this.self = self;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String key) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/*
public String[] getAvatarUrls() {
return avatarUrls;
}
public void setAvatarUrls(String[] avatarUrls) {
this.avatarUrls = avatarUrls;
}
*/
}
class JiraActors {
#SerializedName("id")
private int id;
#SerializedName("displayNme")
private String displayName;
#SerializedName("type")
private String type;
#SerializedName("name")
private String name;
//#SerializedName("avatarUrl")
//private String avatarUrl;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The json it would receive:
{
"self":"http://someserver.com:8080/apps/jira/rest/api/2/project/10741/role/10002",
"name":"Administrators",
"id":10002,
"description":"A project role",
"actors":[
{
"id":12432,
"displayName":"Joe Smith",
"type":"atlassian-user-role-actor",
"name":"joesmi",
"avatarUrl":"/apps/jira/secure/useravatar?size=xsmall&ownerId=dawsmi&avatarId=12245"
},
{
"id":12612,
"displayName":"Smurfette Desdemona",
"type":"atlassian-user-role-actor",
"name":"smudes",
"avatarUrl":"/apps/jira/secure/useravatar?size=xsmall&ownerId=lamade&avatarId=10100"
},
This shows two actors and the format of the json. Please note I did not put a complete json response. It just shows two actors.
In my code, I tried the following to retrieve the actors:
InputStream is = response.getEntityInputStream();
Reader reader = new InputStreamReader(is);
Gson gson = new Gson();
JiraRoleJsonWrapper[] jiraRoleJsonWrapper = gson.fromJson(reader, JiraRoleJsonWrapper[].class);
for (JiraRoleJsonWrapper w : jiraRoleJsonWrapper) {
JiraActors[] a = w.getActors();
String name = a.getName();
It does not find getName for some reason. I am not sure why.
I figured it out.
I change the setActors to
public void setActors(ArrayList<JiraActors> actors) {
this.actors = actors;
}
Then I was able to get the array list and get access to the getName() method of JiraActors.
I wrote a REST web service which is returning JSON as below
[{"id":0,"name":"Vishal","age":"23","dob":"21/1/1992","phone":"9966558","sslc":"90","hsc":"90","college":"90"},
{"id":0,"name":"Karthik","age":"27","dob":"14/8/1988","phone":"995674","sslc":"99","hsc":"100","college":"100"},
{"id":0,"name":"Jeeva","age":"29","dob":"10/1/1987","phone":"77422","sslc":"99","hsc":"99","college":"100"},
{"id":0,"name":"Arya","age":"26","dob":"10/1/1989","phone":"55668","sslc":"100","hsc":"99","college":"99"}]
But I want the output with the "student" appended as below.
{"student":[{"id":0,"name":"Vishal","age":"23","dob":"21/1/1992","phone":"9966558","sslc":"90","hsc":"90","college":"90"},
{"id":0,"name":"Karthik","age":"27","dob":"14/8/1988","phone":"995674","sslc":"99","hsc":"100","college":"100"},
{"id":0,"name":"Jeeva","age":"29","dob":"10/1/1987","phone":"77422","sslc":"99","hsc":"99","college":"100"},
{"id":0,"name":"Arya","age":"26","dob":"10/1/1989","phone":"55668","sslc":"100","hsc":"99","college":"99"}]}
how can I achieve this output?
Below is the Product Class
#XmlRootElement(name="student")
public class Student implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
public Student() {
super();
}
public Student(int id, String name, String age, String dob, String phone,
String sslc, String hsc, String college) {
super();
this.id = id;
this.name = name;
this.age = age;
this.dob = dob;
this.phone = phone;
this.sslc = sslc;
this.hsc = hsc;
this.college = college;
}
private int id;
private String name;
private String age;
private String dob;
private String phone;
private String sslc;
private String hsc;
private String college;
#XmlElement
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlElement
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
#XmlElement
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
#XmlElement
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
#XmlElement
public String getSslc() {
return sslc;
}
public void setSslc(String sslc) {
this.sslc = sslc;
}
#XmlElement
public String getHsc() {
return hsc;
}
public void setHsc(String hsc) {
this.hsc = hsc;
}
#XmlElement
public String getCollege() {
return college;
}
public void setCollege(String college) {
this.college = college;
}
#Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age
+ ", dob=" + dob + ", phone=" + phone + ", sslc=" + sslc
+ ", hsc=" + hsc + ", college=" + college + "]";
}
}
Below is the service class.
#GET
#Path("/student.srv")
#Produces("application/json")
public Response getStudentJson(){
DAOLayer daoLayer=new DAOLayer();
List<Student> studentsList=null;
try {
studentsList=daoLayer.getStudents();
} catch (SQLException e) {
e.printStackTrace();
}
return Response.ok(studentsList).build();
}
Kindly help me to achieve the above mentioned output.
Thanks in Advance.
To get the desired output, you will have to create one single root object containing a List<Student> student and return it:
Root.java
#XmlRootElement(name="root")
public class Root implements Serializable {
#XmlList
private List<Student> student = new ArrayList<Student>();
// getter and setter
}
Service.java
#GET
#Path("/student.srv")
#Produces("application/json")
public Response getStudentJson(){
DAOLayer daoLayer=new DAOLayer();
List<Student> studentsList=null;
try {
studentsList=daoLayer.getStudents();
} catch (SQLException e) {
e.printStackTrace();
}
Root root = new Root();
root.setStudent(studentsList),
return Response.ok(root).build();
}
data_user = "{"id":1,"lastName":"lastName","name":"name","school":{"id":1}}"
public class School {
private int id;
private String name;
}
public class User {
private int id;
private String lastName;
private String name;
private School school;
}
How to deserialize Json data_user to java object User?
I tried with Gson :
Gson gson = new Gson();
User user = gson.fromJson(data_user, User.class)
But I have an error with this code because the Json contains a school which hasn't the school's name.
How Can I serialize the Json to java Object?
School.java
public class School {
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;
}
#Override
public String toString() {
return "School [id=" + id + ", name=" + name + "]";
}
}
User.java
public class User {
private int id;
private String lastName;
private String name;
private School school;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public School getSchool() {
return school;
}
public void setSchool(School school) {
this.school = school;
}
#Override
public String toString() {
return "User [id=" + id + ", lastName=" + lastName + ", name=" + name
+ ", school=" + school + "]";
}
}
Main.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.testgson.beans.User;
public class Main {
private static Gson gson;
static {
gson = new GsonBuilder().create();
}
public static void main(String[] args) {
String j = "{\"id\":1,\"lastName\":\"lastName\",\"name\":\"ignacio\",\"school\":{\"id\":1}}";
User u = gson.fromJson(j, User.class);
System.out.println(u);
}
}
Result
User [id=1, lastName=lastName, name=ignacio, school=School [id=1, name=null]]
Try with the Jackson Library. With Gson with should have not any problem, I tried with the code of #Saurabh and it work well
I'm trying to figure out a way to transform this JSON String into a Java object graph but I'm unable to do so. Below, I've inserted my JSON String, and my two classes. I've verified that its a valid json structure. I've been trying googles api (http://sites.google.com/site/gson/gson-user-guide) but it doesn't map the nested Photo Collection. Any ideas or alternate libraries?
{"photos":{"page":1,"pages":73514,"perpage":50,"total":"3675674","photo":[{"id":"5516612975","owner":"23723942#N07","secret":"b8fb1fda57","server":"5213","farm":6,"title":"P3100006.JPG","ispublic":1,"isfriend":0,"isfamily":0},{"id":"5516449299","owner":"81031835#N00","secret":"67b56722da","server":"5171","farm":6,"title":"Kaiser Boys Volleyball","ispublic":1,"isfriend":0,"isfamily":0}]},"stat":"ok"}
Photos.java
public class Photos {
private int pages;
private int perpage;
private String total;
private List<Photo> photo;
private String stat;
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public int getPerpage() {
return perpage;
}
public void setPerpage(int perpage) {
this.perpage = perpage;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public List<Photo> getPhoto() {
return photo;
}
public void setPhoto(List<Photo> photo) {
this.photo = photo;
}
public String getStat() {
return stat;
}
public void setStat(String stat) {
this.stat = stat;
}
}
Photo.java:
public class Photo {
private String id;
private String owner;
private String secret;
private String server;
private String farm;
private String title;
private int isPublic;
private int isFriend;
private int isFamily;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
public String getFarm() {
return farm;
}
public void setFarm(String farm) {
this.farm = farm;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getIsPublic() {
return isPublic;
}
public void setIsPublic(int isPublic) {
this.isPublic = isPublic;
}
public int getIsFriend() {
return isFriend;
}
public void setIsFriend(int isFriend) {
this.isFriend = isFriend;
}
public int getIsFamily() {
return isFamily;
}
public void setIsFamily(int isFamily) {
this.isFamily = isFamily;
}
}
Use Jackson. It'll take care of converting to and from JSON. It provides multiple ways of approaching conversion, and is well-integrated with frameworks like Spring. Definitely one to know.