The User.java likes this:
public class User { private String userName; private String password; public User() {} public User(String userName, String password) { super(); this.userName = userName; this.password = password; }
And the Group.java likes this:
public class Group { private String groupName; private List<User> lstUser; public Group() {} public Group(String groupName, List<User> lstUser) { super(); this.groupName = groupName; this.lstUser = lstUser; }
Note: in these classes, we overload the default constructor, so we need to define the default constructor for Jackson Without this default constructor, we will receive an error message:
Exception in thread "main" org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class com.lapth82.jackson.example.bean.Group]: can not instantiate from JSON object (need to add/enable type information?)
To work with Jackson, just follow these steps:
Initializing Jackson:
ObjectMapper mapper = new ObjectMapper();
Writing an object to JSON:
String json = mapper.writeValueAsString(lstGroup);
Binding a JSON to Object:
Listat line 4: to bind a JSON to a list we must use TypeReferencelstGroup = mapper.readValue( json, new TypeReference<List<Group>>(){} );
See also: working with XML by using Marshaller and Unmarshaller
For the demonstration, please download Source code from my repository on Github
No comments:
Post a Comment