xxxxxxxxxx
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
// JSON string representing a person object
String json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
// Create Gson object
Gson gson = new Gson();
// Convert JSON string to Person object
Person person = gson.fromJson(json, Person.class);
// Print the converted object
System.out.println(person);
}
}
class Person {
private String name;
private int age;
private String city;
// Getters and setters
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", city='" + city + '\'' +
'}';
}
}
xxxxxxxxxx
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);
xxxxxxxxxx
User u = new User();
u.firstName = "Sample";
u.lastName = "User";
u.email = "sampleU@example.com";
ObjectMapper mapper = new ObjectMapper();
try {
// convert user object to json string and return it
return mapper.writeValueAsString(u);
}
catch (JsonGenerationException | JsonMappingException e) {
// catch various errors
e.printStackTrace();
}
xxxxxxxxxx
String json = "...";
ObjectMapper m = new ObjectMapper();
Set<Product> products = m.readValue(json, new TypeReference<Set<Product>>() {});
xxxxxxxxxx
public class Student {
Integer id;
Map<String,Integer> marks;
List<Address> addresses;
public Student(Integer id, Map<String, Integer> marks, List<Address> addresses) {
this.id = id;
this.marks = marks;
this.addresses = addresses;
}
}
class Address {
String addrType;
Integer houseNo;
String streetName;
String countryName;
House house;
public Address(String addrType, Integer houseNo, String streetName, String countryName, House house) {
this.addrType = addrType;
this.houseNo = houseNo;
this.streetName = streetName;
this.countryName = countryName;
this.house = house;
}
}
class House {
Integer noOfRooms;
String houseType;
Integer noOfWindows;
public House(Integer noOfRooms, String houseType, Integer noOfWindows) {
this.noOfRooms = noOfRooms;
this.houseType = houseType;
this.noOfWindows = noOfWindows;
}
}