I have a java class like :
public class Sclass {
private Student student;
private Teacher teacher;
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
}
public class Teacher {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
I want to use Sclass in a rest service and thus want a json for the same, please assist.
Example using gson:
Student student = new Student();
student.setName("Student 1");
student.setAge(18);
Teacher teacher = new Teacher();
teacher.setName("Teacher 1");
Sclass sclass = new Sclass();
sclass.setStudent(student);
sclass.setTeacher(teacher);
Gson gson = new Gson();
String json = gson.toJson(sclass);
System.out.println(json);
Output:
{"student":{"name":"Student 1","age":18},"teacher":{"name":"Teacher 1"}}
Related
I want to convert the following bean class to JSON object by using Jackson library
public class Student {
String name ;
int id ;
List<Address> address;
}
I want following json
{
"Name" : "sys1",
"Id" : 1,
"address" : [some address]
}
Can anyone help me how to achieve this ?.
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JavaToJson {
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
try {
List<Address> addrList = new ArrayList<>();
Address addr = new Address();
addr.setArea("ABC");
addr.setCity("XYZ");
addrList.add(addr);
Student std = new Student();
std.setName("Rahul");
std.setId(1);
std.setAddress(addrList);
String json = objectMapper.writeValueAsString(std);
System.out.println(json);
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Student {
String name;
int id;
List<Address> address;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public List<Address> getAddress() {
return address;
}
public void setAddress(List<Address> address) {
this.address = address;
}
}
class Address {
String area;
String city;
public String getArea() {
return this.area;
}
public void setArea(String area) {
this.area = area;
}
public String getCity() {
return this.area;
}
public void setCity(String city) {
this.city = city;
}
}
JSON
{
"schools": [
{
"id": 1,
"name": "School A"
},
{
"id": 2,
"name": "School B"
}
],
"students": [
{
"id": 1,
"name": "Bobby",
"school": 1
}
]
}
How would I map the JSON into the following classes such that Bobby's school is mapped to the already instantiated School A.
public class School {
private Integer id;
private String name;
}
public class Student {
private Integer id;
private String name;
private School school;
}
I've tried some weird stuff with the Student class...
public class Student {
private Integer id;
private String name;
private School school;
#JsonProperty("school")
public void setSchool(Integer sid) {
for (School school : getSchools()) {
if (school.id == sid) {
this.school = school;
break;
}
}
}
}
The problem I'm having is that both the schools and the students are being parsed from the JSON at the same time, so I'm not sure how to get a list of the schools. Maybe I should parse these separately so I have the list of schools first?
Jackson will do it for you. Just annotate your objects with #JsonIdentityInfo:
#JsonIdentityInfo(scope=School.class, generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
public class School {
private Integer id;
private String name;
public School() {
}
public School(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
#JsonIdentityInfo(scope=Student.class, generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
public class Student {
private Integer id;
private String name;
private School school;
public Student() {
}
public Student(Integer id, String name, School school) {
this.id = id;
this.name = name;
this.school = school;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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;
}
}
public static void main(String[] args) throws IOException {
School school = new School(1, "St Magdalene's");
Student mary = new Student(1, "Mary", school);
Student bob = new Student(2, "Bob", school);
Student[] students = new Student[] {mary, bob};
// Write out
String serialized = mapper.writeValueAsString(students);
System.out.println("Serialized: " + serialized);
// Read in
Student[] deserialized = mapper.readValue(serialized, Student[].class);
}
With classes defined as below:
#JsonIdentityInfo(property = "id", generator = ObjectIdGenerators.PropertyGenerator.class)
class School {
public Integer id;
public String name;
}
class Student {
public Integer id;
public String name;
#JsonIdentityReference(alwaysAsId = true)
public School school;
}
class All {
public List<School> schools;
public List<Student> students;
}
This works exactly as You intended:
#Test
public void test() throws JsonProcessingException {
var json = "{" +
"\"schools\":[" +
"{\"id\":1,\"name\":\"School A\"}," +
"{\"id\":2,\"name\":\"School B\"}" +
"]," +
"\"students\":[" +
"{\"id\":1,\"name\":\"Bobby\",\"school\":1}" +
"]" +
"}";
var mapper = new ObjectMapper();
var all = mapper.readValue(json, All.class);
Assertions.assertThat(all.students.get(0).school).isSameAs(all.schools.get(0));
}
While sorting an arraylist of Customer Class(user defined) having name and age as attributes on the basis of name, Collections.sort() method is showing error that "the type java.util.Comparator is not resolved.it is indirectly referenced from required .class file.
package comparable;
import java.util.*;
public class Tester {
public static void main(String[] args){
List<Customer> custtlist=new ArrayList<Customer>();
Customer c1=new Customer("vikas",1);
Customer c2=new Customer("mittal",2);
custtlist.add(c1);
custtlist.add(c2);
System.out.println("Before Sorting");
Iterator<Customer> iterator = custtlist.iterator();
while(iterator.hasNext()){
Customer customer = (Customer) iterator.next();
System.out.println(customer.getCustname());
}
Collections.sort(custtlist);
System.out.println("After Sorting");
iterator = custList.iterator();
while (iterator.hasNext()) {
Customer customer = (Customer) iterator.next();
System.out.println(customer.getCustName());
}
}
}
//Customer Class
package comparable;
public class Customer implements Comparable<Customer> {
private String custname;
private int age;
public Customer(String custname, int age) {
this.custname = custname;
this.age = age;
}
public Customer() {
}
public String getCustname() {
return custname;
}
public void setCustname(String custname) {
this.custname = custname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int compareTo(Customer c){
return this.custname.compareTo(c.getCustname());
}
}
You have an awful lot of typos in the code. After I corrected them, the compilation was successful. I took the liberty to make some improvements and styling.
import java.util.*;
public class Tester {
public static void main(String[] args){
List<Customer> customersList = new ArrayList<Customer>();
Customer c1 = new Customer("vikas", 1);
Customer c2 = new Customer("mittal", 2);
customersList.add(c1);
customersList.add(c2);
System.out.println("Before Sorting");
for(Customer customer : customersList) {
System.out.println(customer.getName());
}
Collections.sort(customersList);
System.out.println("\nAfter Sorting");
for(Customer customer : customersList) {
System.out.println(customer.getName());
}
}
}
public class Customer implements Comparable<Customer> {
private String name;
private int age;
public Customer(String name, int age) {
this.name = name;
this.age = age;
}
public Customer() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int compareTo(Customer c){
return this.name.compareTo(c.getName());
}
}
In an ArrayList I have two different objects,
Student and Employee. I want to iterate through them one by one. I am able to iterate through the list and use the Employee objects but not the Student objects.
I have the following code:
package javaCollections;
import java.util.ArrayList;
import java.util.Iterator;
class Employee {
#Override
public String toString() {
return "employee [name=" + name + ", age=" + age + "]";
}
public String name;
public int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
Employee(String name, int age) {
this.age = age;
this.name = name;
}
}
class Student {
#Override
public String toString() {
return "student [stud_name=" + stud_name + ", rollNumber=" + rollNumber
+ "]";
}
String stud_name;
int rollNumber;
public Student(String stud_name, int rollNumber) {
super();
this.stud_name = stud_name;
this.rollNumber = rollNumber;
}
public String getStud_name() {
return stud_name;
}
public void setStud_name(String stud_name) {
this.stud_name = stud_name;
}
public int getRollNumber() {
return rollNumber;
}
public void setRollNumber(int rollNumber) {
this.rollNumber = rollNumber;
}
}
public class Arraylist {
ArrayList<Object> emparray;
public void addemp() {
Employee emp = new Employee("abc", 12);
emparray = new ArrayList<Object>();
emparray.add(emp);
Employee emp1 = new Employee("def", 12);
emparray.add(emp1);
Student std = new Student("efg", 123);
Student std1 = new Student("xyz", 123);
emparray.add(std);
emparray.add(std1);
}
public void iterateemp() {
/*
* Iterator<Object> itr=emparray.iterator();
*
* while(itr.hasNext()) { System.out.println(itr.next()); }
*/
for (Object e : emparray) {
System.out.println(((Employee) e).getAge());
System.out.println(((Employee) e).getName());
}
}
public static void main(String[] args) {
Arraylist al = new arraylist();
al.addemp();
al.iterateemp();
}
}
can someone please help me on this?
What you need to do is check the instance of the object.
for (Object e : emparray) {
if(e instanceof employee) {
System.out.println(((employee) e).getAge());
System.out.println(((employee) e).getName());
} else if(e instanceof student) {
// do something else
}
}
}
IMO this is a bad design.
The best practice is to create common base called Person that has shared fields like name. Then you can replace Object with Person in the loop.
import java.util.ArrayList;
import java.util.Iterator;
interface Person{
public String getName();
public void setName(String name);
}
class employee implements Person{
#Override
public String toString() {
return "employee [name=" + name + ", age=" + age + "]";
}
public String name;
public int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
employee(String name, int age) {
this.age = age;
this.name = name;
}
}
class student implements Person{
#Override
public String toString() {
return "student [stud_name=" + name + ", rollNumber=" + rollNumber
+ "]";
}
String name;
int rollNumber;
public student(String stud_name, int rollNumber) {
super();
this.name = stud_name;
this.rollNumber = rollNumber;
}
public int getRollNumber() {
return rollNumber;
}
public void setRollNumber(int rollNumber) {
this.rollNumber = rollNumber;
}
#Override
public String getName() {
return name;
}
#Override
public void setName(String name) {
this.name=name;
}
}
public class arraylist {
ArrayList<Person> emparray;
public void addemp() {
employee emp = new employee("abc", 12);
emparray = new ArrayList<Person>();
emparray.add(emp);
employee emp1 = new employee("def", 12);
emparray.add(emp1);
student std = new student("efg", 123);
student std1 = new student("xyz", 123);
emparray.add(std);
emparray.add(std1);
}
public void iterateemp() {
for (Person e : emparray) {
if (e instanceof employee) {
System.out.println(((employee) e).getAge());
}else{
/// do for student
}
System.out.println(e.getName());
}
}
public static void main(String[] args) {
arraylist al = new arraylist();
al.addemp();
al.iterateemp();
}
}
for (Object e : emparray) {
if(e instanceof employee) {
System.out.println(((employee) e).getAge());
System.out.println(((employee) e).getName());
} else if(e instanceof student) {
System.out.println(((student) e).getRollNumber());
System.out.println(((student) e).getStud_name());
}
}
}
I am very new and learning java,I want to perform deep cloning without serialization ,I read some articles from internet and still in doubt about deep cloning without serialization.So i want to know is there any other rules that I have to follow to do deep cloning, below is my program
Department.java
package com.deepclone;
public class Department {
private int id;
private String name;
public Department(int id, String name) {
this.id = id;
this.name = 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;
}
}
Employee.java
package com.deepclone;
public class Employee implements Cloneable {
private String employeeId;
private String empName;
private Department department;
public Employee(String employeeId, String empName, Department department) {
this.employeeId = employeeId;
this.empName = empName;
this.department = department;
}
#Override
protected Object clone() throws CloneNotSupportedException {
Employee employee = new Employee(employeeId, empName, new Department(
department.getId(), department.getName()));
return employee;
}
public String getEmployeeId() {
return employeeId;
}
public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
}
TestCloning.java
package com.deepclone;
public class TestClonning1 {
public static void main(String[] args) throws CloneNotSupportedException {
Department hrDepartment = new Department(10, "HR");
Employee employee = new Employee("1", "rajeev", hrDepartment);
System.out.println(employee.getDepartment().getName());
Employee cloneEmployee = (Employee) employee.clone();
System.out.println(cloneEmployee.getDepartment().getName());
cloneEmployee.getDepartment().setName("it");
System.out.println(employee.getDepartment().getName());
System.out.println(cloneEmployee.getDepartment().getName());
}
}
output
HR
HR
HR
it
is there any other alternative to achive deep cloning without serialization...if yes then give link.
Try this Java Deep-Cloning Library
Cloner cloner = new Cloner();
MyClass other = ...;
MyClass clone = cloner.deepClone(other);