1

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.

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

interesting, I was using it in Android, and read somewhere I could use GSON. Will explore further. thanks
1

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.

Comments

0
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;
}

1 Comment

Welcome to SO, some explanation regarding your answer would be a good idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.