bsr
bsr

Reputation: 58662

Java pattern to create objects

My recent exposure was mostly to non OOP languages, so wonder any pattern or practice to do the below.

I need to write a function, which takes a json string (json array of objects) and produces list of objects (say Student). I checked the creational patterns, but doesn't seems to fit. Do you think I should write a helper class just to create these objects.

Upvotes: 1

Views: 139

Answers (3)

jahroy
jahroy

Reputation: 22692

You could write a method that takes a JSON string and a class object and returns list containing objects of the given type:

public static <T> List<T> parseJsonList(String json, Class<T> theClass) {
    // do stuff
}

Usage:

List<Student> studentList = parseJsonList(studentJsonText, Student.class);
List<Teacher> teacherList = parseJsonList(teacherJsonText, Teacher.class);

As @Jeff mentions, it would probably be better to create constructors for Student and Teacher that accept a JSON string.

Or you could have a static method in the Student class that creates a List of Students from a JSON string.

Or you could create an ObjectFactory class that creates objects of different kinds.

Upvotes: 1

user1658644
user1658644

Reputation: 43

public class Action {

  public static class Response {

    private int _resultCode;
    private int _count = 0;

    public Response() {}

    public int getResultCode() { return _resultCode; }
    public int getCount() { return _count; }

    public void setResultCode(int rc) { _resultCode = rc; }
    public void setCount(int c) { _count = c; }
  }

  private List<Response> responses = new ArrayList<Response>();
  private String _name;
}

Upvotes: 0

asteri
asteri

Reputation: 11572

If you have a kind of util class already, this kind of function would fit nicely in that class. I wouldn't make a completely separate class just for this. For instance, something like:

public static List<Student> parseJsonToStudents(String jsonData) ...

You could, however, have a constructor in your Student class which accepts a json String as a parameter and constructs the Student object from that. That would definitely be taking advantage of OO principles. But the GSON package renders a lot of that kind of thing obsolete and you might not want to bother programming it yourself. It has in it fromJson() and toJson() methods which will parse the data and construct the objects for you.

Upvotes: 1

Related Questions