'Mapping java class To JSON By Using Jackson
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 ?.
Solution 1:[1]
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;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Java Team |
