First line creates a new Restaurant object. second line also creates a new Restaurant object but using a JSON string, you need Jackson library for this task. You don't need first line if your requirement is only to create an object.
lets say your Restaurant class looks like this.
class Restaurant {
private String id;
private String name;
//getters and setters
}
and you have a JSON look likes this.
String json = "{ \"id\" : \"1\", \"name\" : \"My Restaurant\" }";
Then you can create Restaurant object using second line
Restaurant restaurant = objectMapper.readValue(json, Restaurant.class);
after that you can read json values from restaurant object.
System.out.println(restaurant.getName());
output:
My Restaurant
Answer from Vimukthi on Stack OverflowVideos
First line creates a new Restaurant object. second line also creates a new Restaurant object but using a JSON string, you need Jackson library for this task. You don't need first line if your requirement is only to create an object.
lets say your Restaurant class looks like this.
class Restaurant {
private String id;
private String name;
//getters and setters
}
and you have a JSON look likes this.
String json = "{ \"id\" : \"1\", \"name\" : \"My Restaurant\" }";
Then you can create Restaurant object using second line
Restaurant restaurant = objectMapper.readValue(json, Restaurant.class);
after that you can read json values from restaurant object.
System.out.println(restaurant.getName());
output:
My Restaurant
The ObjectMapper will parse the JSON in jsonString to a Restaurant object (that's why you give it Restaurant.class as a parameter). It will then store the created object in the restaurant variable.