1

I'm creating a client that can send different requests to a server. Part of my goal is to not have any large dependencies.

A request can look as following:

{
  "method": "getUser",
  "methodParameters": {
    "a": "b",
    "c": "d",
    "e": "f",
    "data": {
      "u": "v",
      "x": "y"
    }
  },
  "version": "1.3"
}

The content of the data object is different for every type of request method. My question is, what would be the best "Java-way" to build these JSON requests dynamically?

So far I've only come up with a couple alternatives that I don't think is the best way to do it..

Example 1

Just a normal POJO with some set/getters and a SimpleJSON object.

public class MethodOne {
    JSONObject data = new JSONObject();

    private void setX(String x) {
        data.put("x", x);
    }

    private String getX() {
        return (String) data.get("x");
    }

    private void setY(String y) {
        data.put("y", y);
    }

    private String getY() {
        return (String) data.get("y");
    }
}

Example 2

public class RequestData {
    public JSONObject methodOne(String x, String y) {
        JSONObject data = new JSONObject();
        data.put("x", x);
        data.put("y", y);
        return data;
    }

    public JSONObject methodTwo(String a, String b) {
        JSONObject data = new JSONObject();
        data.put("a", a);
        data.put("b", b);
        return data;
    }
}

So what do you think. Is any of the above solutions better for the job, or is there a third solution that I have yet to come up with? Thanks.

anony115511
  • 172
  • 2
  • 2
  • 13

1 Answers1

1

Note your example 1 is not a POJO, it's a wrapped JSONObject.

GSON can be used with a true POJO:

class BagOfPrimitives {
  private int value1 = 1;
  private String value2 = "abc";
  private transient int value3 = 3;
  //setters/getters optional
}

BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);

There is also a getAsJsonObject method if you need that rather than a String. See also https://stackoverflow.com/a/13434887/360211 about that.

Community
  • 1
  • 1
weston
  • 54,145
  • 21
  • 145
  • 203