Home > Mobile >  Need advice to structure and modify a JSON-payload in Java
Need advice to structure and modify a JSON-payload in Java

Time:09-30

Here is a simplified JSON payload that I want to be able to change (the original one is much longer)

{
  "request": {
    "jsonRequest": {
      "Alpha": {
        "Bravo": [
          {
            "Delta": "something"
          }
        ],
        "Desert": [
          {
            "id": 1,
            "name": "Lena",
            "age": "25",
            "city": "Florida",
            "street": "Florida Street"
          },
          {
            "id": 2,
            "name": "Moa",
            "age": "21",
            "city": "Mexico",
            "street": "Mexico Street"
          },
          {
            "id": 3,
            "name": "Nils",
            "age": "29",
            "city": "Tampas",
            "street": "Tampas Street"
          }
        ]
      }
    }
  }
}

Most of the values should be hardcoded and not changed, however, there are some fields I need to be able to modify before I send it as PUT-request.

So, here is what I did: I created a java class and a method to return this String. Then I'll be using String.format() to solve my problem.

public class myClass {

  /* The string I want to send - note the %s which is the sub-strings that I want to be able to modify */
  private String payload = "{\r\n\"request\":{\r\n\"jsonRequest\":{\r\n\"Alpha\":{\r\n\"Bravo\":[\r\n{\r\n\"Delta\":\"something\"\r\n}\r\n],\r\n\"Desert\":[\r\n{\r\n\"id\":1,\r\n\"name\":\"%s\",\r\n\"age\":\"25\",\r\n\"city\":\"Florida\",\r\n\"street\":\"%s\"\r\n},\r\n{\r\n\"id\":2,\r\n\"name\":\"Moa\",\r\n\"age\":\"21\",\r\n\"city\":\"Mexico\",\r\n\"street\":\"%s\"\r\n},\r\n{\r\n\"id\":3,\r\n\"name\":\"Nils\",\r\n\"age\":\"29\",\r\n\"city\":\"Tampas\",\r\n\"street\":\"TampasStreet\"\r\n}\r\n]\r\n}\r\n}\r\n}\r\n}"

 // Method to return this string
 public String getPayload() {return this.payload;}
}

Then in the main class, I call this method like this:

String temp = new myClass().getPayload();
String payload = String.format(temp, "Lena", "Florida Street", "Mexico Street");  

This solves the issue, but I think I've stepped on too many toes with my approach to solve it. I gladly take advice in how to do this is a more efficient and readable way, because right now I'll be the only one to understand what is going on.

CodePudding user response:

You can use a more structured way using Gson or Jackson libraries. Create your POJO class and annotate it with these libraries' specific annotations. The POJO depth level is related to your design. The easiest way is to create a Map<String, Object> and fill it with what you want as follow:

    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    Map<String, Object> items = new LinkedHashMap<>();
    items.put("request", Map.of(
            "jsonRequest", Map.of(
                    "Alpha", Map.of(
                            "Bravo", List.of("Delta", "something"),
                            "Desert", List.of(
                                    Map.of("id", 1),
                                    Map.of("id", 2),
                                    Map.of("id", 3),
                                    Map.of("id", 4)
                            )
                    )
            )));

    System.out.println(mapper.writeValueAsString(items));

The ObjectMapper will produce something like the below:

{
  "request" : {
    "jsonRequest" : {
      "Alpha" : {
        "Bravo" : [ "Delta", "something" ],
        "Desert" : [ {
          "id" : 1
        }, {
          "id" : 2
        }, {
          "id" : 3
        }, {
          "id" : 4
        } ]
      }
    }
  }
}

The more strict way is to design your POJO with more details. The jackson-object-mapper is used to achieve the goals.

static class Request {
    private Map<String, JsonRequest> items = new LinkedHashMap<>();

    @JsonAnyGetter
    public Map<String, JsonRequest> getItems() {
        return items;
    }

    public void addItem(String property, JsonRequest value) {
        items.put(property, value);
    }
}

static class JsonRequest {
    private Map<String, List<JsonRequestItem>> items = new LinkedHashMap<>();

    @JsonAnyGetter
    public Map<String, List<JsonRequestItem>> getItems() {
        return items;
    }

    public void addItem(String property, List<JsonRequestItem> value) {
        items.put(property, value);
    }
}

static class JsonRequestItem {
    private Map<String, Object> items = new LinkedHashMap<>();

    @JsonAnyGetter
    public Map<String, Object> getItems() {
        return items;
    }

    public void addItem(String property, Object value) {
        items.put(property, value);
    }
}

You can test the structure using the code below:

public static void main(String[] args) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    Request request = new Request();
    JsonRequest alpha = new JsonRequest();
    alpha.addItem("Bravo", List.of(
            new JsonRequestItem() {{
                addItem("Delta", "something");
            }}
    ));

    alpha.addItem("Desert", List.of(
            new JsonRequestItem() {{
                addItem("id", 1);
                addItem("name", "Lena");
                addItem("age", "25");
                addItem("city", "Florida");
                addItem("street", "Florida Street");
            }},
            new JsonRequestItem() {{
                addItem("id", 2);
                addItem("name", "Moa");
                addItem("age", "21");
                addItem("city", "Mexico");
                addItem("street", "Mexico Street");
            }},
            new JsonRequestItem() {{
                addItem("id", 3);
                addItem("name", "Nils");
                addItem("age", "29");
                addItem("city", "Tampas");
                addItem("street", "Tampas Street");
            }}
    ));

    request.addItem("Alpha", alpha);

    System.out.println(mapper.writeValueAsString(request));
}

Then the result will be similar:

{
  "Alpha" : {
    "Bravo" : [ {
      "Delta" : "something"
    } ],
    "Desert" : [ {
      "id" : 1,
      "name" : "Lena",
      "age" : "25",
      "city" : "Florida",
      "street" : "Florida Street"
    }, {
      "id" : 2,
      "name" : "Moa",
      "age" : "21",
      "city" : "Mexico",
      "street" : "Mexico Street"
    }, {
      "id" : 3,
      "name" : "Nils",
      "age" : "29",
      "city" : "Tampas",
      "street" : "Tampas Street"
    } ]
  }
}
  • Related