{"users":[{"name":"Albert","id":1},{"name":"Mandy","id":2}]}
Steps:
1. Create a User object which have two attributes (id and name)
2. Create a getUsers method to retrieve dummy user collection
3. Create buildUserJson() to build JSON string from List of User
package albert.practice.json; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; import lombok.AllArgsConstructor; import lombok.Data; import lombok.ToString; import lombok.extern.slf4j.Slf4j; @Slf4j public class JsonObjectTest { public static void main(String[] args) { JsonObjectTest test = new JsonObjectTest(); String userJSON = test.buildUserJson(); log.debug("user JSON = " + userJSON); } public String buildUserJson() { List<User> users = getUsers(); JSONObject dataset = new JSONObject(); users.stream().forEach(u -> addToDataset(u, dataset)); return dataset.toString(); } private static void addToDataset(User user, JSONObject dataset) { JSONObject userObj = new JSONObject(); userObj.put("id", user.getId()); userObj.put("name", user.getName()); // use the accumulate function to add to an existing value. The value // will now be converted to a list dataset.accumulate("users", userObj); } public List<User> getUsers() { User albert = new User(1, "Albert"); User mandy = new User(2, "Mandy"); return Arrays.asList(albert, mandy); } @Data @AllArgsConstructor @ToString private static class User { private Integer id; private String name; } }
If you would like to parse JSON string to List of User, you can check parseUserJson(String json)
public List<User> parseUserJson(String json) { JSONObject jsonObj = new JSONObject(json); JSONArray userArray = (JSONArray) jsonObj.get("users"); List<User> users = new ArrayList<>(); userArray.forEach(u -> addToList(u, users)); return users; } private void addToList(Object user, List<User> users) { JSONObject userObj = (JSONObject) user; Integer id = (Integer) userObj.get("id"); String name = (String) userObj.get("name"); users.add(new User(id, name)); }
Reference
[1] http://www.studytrails.com/java/json/java-org-json.jsp