Although I generally advocate using something like GSON or Jackson for JSON conversions for you, it's pretty easy to minimize it yourself if you are in a limited environment (like Android) and don't want to bind a lot of dependencies.
public class JsonHelper { public static String convertToJSON(List<GraphUser> users) { StringBuilder sb = new StringBuilder(); for (GraphUser user : users) { sb.append(convertToJSON(user)); } return sb.toString(); } public static String convertToJSON(GraphUser user) { return new StringBuilder() .append("{") .append("\"id\":").append(user.getId()).append(",") .append("\"admin\":").append(user.isAdmin() ? "true" : "false").append(",") .append("\"name\":\"").append(user.getName()).append("\",") .append("\"email\":\"").append(user.getEmail()).append("\"") .append("}") .toString(); } }
Obviously, you can make the toJSON() method on GraphUser to put the logic if you want. Or use an injectable json helper library instead of static methods (I would). Or any number of other abstractions. Many developers prefer to share the representation of model objects with their own object, including me. Personally, I could simulate something like this if I wanted to avoid the dependencies:
interface Marshaller<F,T> using the methods T marshall(F obj) and F unmarshall(T obj)interface JsonMarshaller<F> extends Marshaller<String>class GraphUserMarshaller implements JsonMarshaller<GraphUser>class GraphUserCollectionMarshaller implements JsonMarshaller<Collection<GraphUser>> , which can perform type checking or use a visitor template or something to determine the best way to represent this type of collection of objects.
Along the way, I'm sure you will find multiple code to extract into super- or compound classes, especially after you start modeling collectible marshalers this way. Although this can be quite verbose (and tedious), it works especially well in resource-limited environments where you want to limit the number of libraries you depend on.
source share