0

For example, at the moment I am getting a list of restaurants from a Google API. then I have to create a a restaurant class with getters and setters, then I have to create objects of that class and populate them with each field from the returned json manually.

Is there another way to do this quicker than manually doing all the work?

124697
  • 22,097
  • 68
  • 188
  • 315

2 Answers2

0

The best thing is to find libraries for that particular API. Failing that, you could consume the JSON without mapping them to Java Beans (i.e. just parse the JSON and work with the parsed JSON by doing parsed.getString("city_name") etc.). Jackson is a good library to do that.

You could also try generating a JSON schema out of the returned JSON, then using that to auto generate Java Beans code, and then use this with a JSON library like Jackson. I tried this once but it seems that you have to fix the generated JSON schema quite a bit as the automatic schema generation tools referenced above isn't very good at the moment.

Community
  • 1
  • 1
Enno Shioji
  • 26,542
  • 13
  • 70
  • 109
0

What I do is just create an object that matches the returned json string and place the values into the object using gson.fromjson()

Object.

public class Return {
    private String Status;
    private String[] Data;

    public Return(String Status, String[] Data){
        this.Status=Status;
        this.Data=Data;
    }
    public String getStatus() { return Status; }

    public String[] getData() { return Data; }
}

Code to populate Object.

        java.lang.reflect.Type listType = new TypeToken<Return>(){}.getType();
        Return return2= new Gson().fromJson(myresponse.toString(), listType);
Codeguy007
  • 891
  • 1
  • 12
  • 32