0

please help me to create the body request from the following output:

{
  "categories": [
    {
      "categoryId": "4654-456465-4564",
      "fields": {
        "4564654-454646-4564": "Ano",
        "4564654-454646-4561": "Super"
      }
    }
  ],
  "lastUpdate": "1231",
  "controlStructureId": "4654-456465-4564",
  "controlId": "4654-456465-4564",
  "vehicleId": "4654-456465-4564"
}

My code here, but It's not correct, because I have unwanted [ ] in * fields* section

public void testPOST() {
        Map<String, Object> jsonBodyUsingMap = new HashMap<String, Object>();

        jsonBodyUsingMap.put("categories", Collections.singletonList(new HashMap<String, Object>() {
            {
                put("categoryId", "4654-456465-4564");
                put("fields", Arrays.asList(new HashMap<String, Object>() {{
                        put("4564654-454646-4561", "Super");
                        put("4564654-454646-4564", "Ano");
                }}
                ));
            }
        }
        ));
        jsonBodyUsingMap.put("lastUpdate", "1231");
        jsonBodyUsingMap.put("controlStructureId", "4654-456465-4564");
        jsonBodyUsingMap.put("controntrolId", "4654-456465-4564");
        jsonBodyUsingMap.put("vehicleId", "4654-456465-4564");
Toyota
  • 33
  • 1
  • 5
  • `fields` must be a `Map` and not an `Array`. So no need for `Arrays.asList(...)` just use the `HashMap` you are already creating. But you should probably use a dedicated JSON library like for instance [Jackson](https://github.com/FasterXML/jackson) – derpirscher Nov 02 '20 at 12:52

2 Answers2

0

It appears that you're wrapping your key/value object, the HashMap in an Array method. If you lose that, you'll get keys/values and not "brackets" (keyless list of values)

put("fields", new HashMap<String, Object>() {{
    put("4564654-454646-4561", "Super");
    put("4564654-454646-4564", "Ano");
}});
Cameron Hurd
  • 4,836
  • 1
  • 22
  • 31
0

You can just remove Arrays.asList() from * fields* and let only the hash map

public void testPOST() {
        Map<String, Object> jsonBodyUsingMap = new HashMap<String, Object>();

        jsonBodyUsingMap.put("categories", Collections.singletonList(new HashMap<String, Object>() {
            {
                put("categoryId", "4654-456465-4564");
                put("fields", new HashMap<String, Object>() {{
                        put("4564654-454646-4561", "Super");
                        put("4564654-454646-4564", "Ano");
                }}
                );
            }
        }
        ));
        jsonBodyUsingMap.put("lastUpdate", "1231");
        jsonBodyUsingMap.put("controlStructureId", "4654-456465-4564");
        jsonBodyUsingMap.put("controntrolId", "4654-456465-4564");
        jsonBodyUsingMap.put("vehicleId", "4654-456465-4564");
Abanoub Hany
  • 557
  • 4
  • 7