Convert JSON To Class Object In Java
In this example we will see how to convert json string to java object with spring framework and jackson apis.
Example:
Json:
String name=
"{
"name" : "Text1"
}";
Create a class for json attribute:
class User{
String name;
}
import com.fasterxml.jackson.anotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
public class ConvertJsonToJavaClassObject{
public static void main(String args[]){
String userString = //json string
ObjectMapper objectMapper = new Jackson2ObjectMapperBuilder().build();
User user = objectMapper.readValue(userString, User.class);
}
}
JSON to Collection object:
json to list:Jsong string:
String name =
{
users:[{
"name" :"name1"
},
{
"name" :"name2"
}
]
}
Java Example:
class Users {
List<User> users;
}
String userString = //json string
ObjectMapper objectMapper = new Jackson2ObjectMapperBuilder().build();
CollectionType type = objectMapper .getTypeFactory().constructCollectionType(List.class, Users .class);
User user = objectMapper.readValue(userString, type);
No comments:
Post a Comment