How to convert Json to Java Object, Deserializing Json - java

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

Related

Problem writing a builder for a class in java

I have problem writing a builder for a class in java. It always gives me an error saying could not find symbol.
class Company {
private String name;
private String address;
private String contact;
private int sizeOfEmployee;
private Date createdTime;
#Override
public String toString() {
return "Company{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
", contact='" + contact + '\'' +
", sizeOfEmployee=" + sizeOfEmployee +
", createdTime=" + createdTime +
'}';
}
public static class builder {
private String name;
private String address;
private String contact;
private int sizeOfEmployee;
private Date createdTime;
public builder Name (String name){
this.name = name;
return this;
}
public builder address(String address){
this.address = address;
return this;
}
public builder contact(String contact){
this.contact = contact;
return this;
}
public builder size(int sizeOfEmployee){
this.sizeOfEmployee = sizeOfEmployee;
return this;
}
public builder date(Date createdTime){
this.createdTime = createdTime;
return this;
}
}
}
I would like to write a builder that could print out my Company class. Could anyone tell me why my builder is not working? I search for how to write a builder and try to copy the method. But it's not working here. It gives me an error saying error can not find symbol.
If I call
Company abc = Company.builder().name("abc").address("Virginia").createdTime(new Date()).sizeOfEmployee(300).contact("12345").build();
It will print out
Company{name='abc', address='Virginia', contact='12345', sizeOfEmployee=300, createdTime=Wed Oct 21 11:50:41 EDT 2020}
You are calling static method builder 'Company.builder()' which does not exists.
You can solve the problem this way:
public class Company {
private String name;
private String address;
public static CompanyBuilder builder() {
return new CompanyBuilder();
}
private static class CompanyBuilder {
private final Company company = new Company();
public CompanyBuilder name(String name){
company.name = name;
return this;
}
public CompanyBuilder address(String address){
company.address = address;
return this;
}
public Company build() {
return company;
}
}
public static void main(String[] args) {
System.out.println(Company.builder().name("name").address("address").build());
}
}
I would suggest Lombok for java projects. With one annotation #Builder including the Lombok plugin and dependency you can solve the problem, also you can use a lot of features instead of boilerplate code.
import lombok.Builder;
import lombok.ToString;
#Builder
#ToString
public class Company {
private String name;
private String address;
public static void main(String[] args) {
System.out.println(Company.builder().name("name").address("address").build());
}
}

json and wrapper for gson

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.

Produce JSON with name of the object from REST web services in Java

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

Gson, parsing json innerclass list, javabean

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,"em‌​ai‌​l":"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,'em‌​ai‌​l':'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.

Parsing nested objects in FIT

I am using Framework for Integrated Test. I know how to use ColumnFixture, RowFixture and ActionFixture basically. Now my problem is, if I have nested objects like Customer object is holding Address object with some fields, how can I parse such kind of objects.
ex:
package com.sample;
import java.sql.Date;
public class Customer {
private String name;
private int no;
private Date dob;
private Address address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
#Override
public String toString() {
return "Customer [name=" + name + ", no=" + no + ", dob=" + dob
+ ", address=" + address + "]";
}
}
package com.sample;
public class Address {
private int dno;
private String street;
private String city;
public int getDno() {
return dno;
}
public void setDno(int dno) {
this.dno = dno;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#Override
public String toString() {
return "Address [dno=" + dno + ", street=" + street + ", city=" + city
+ "]";
}
}
Now, in my my fixture, I want to check (using ActionFixture) getCustomer() method that returns customer object. Now in the parse(String s, Type) where 's' is string format of customer object coming from input file, how can I convert it into Customer object.
Is my approach proper?

Categories

Resources