Swapnil
Swapnil

Reputation: 13

Handling empty JSON

I need to send following JSON in API BODY POST request:

{
    "name": "",
    "type": "TEMP",
    "shared": false,
    "search": {       
    },
    "order": [
    ]
}

In my MainBody.java, declared

private String name;
private String type;
private boolean shared;
private JSON search;
private Object order;

and defined getters and setters.

In Payload.java,

    MainBody mb = new MainBody();
    mb.setName("");
    mb.setType("TEMP");
    mb.setShared(false);
    mb.setSearch(null);
    mb.setOrder(new ArrayList<>());
    
    ObjectMapper om =  new ObjectMapper();
    
    String myData = om.writerWithDefaultPrettyPrinter().writeValueAsString(mb);
    System.out.println(myData);

results

{
  "name" : "",
  "type" : "TEMP",
  "shared" : false,
  "search" : null,
  "order" : [ ]
}

Please assist with how search as { } can be achieved as per expected JSON instead of null.

TIA.

Upvotes: 1

Views: 1768

Answers (3)

Swapnil
Swapnil

Reputation: 13

Issue resolved after using JSONMapper.

Upvotes: 0

Vojtěch V&#225;chal
Vojtěch V&#225;chal

Reputation: 51

I would try something like this:

    mb.setSearch(new JSON());

This way you create empty object and there should be only {}. It also depends on which JSON library do you use.

Upvotes: 0

Frank Riccobono
Frank Riccobono

Reputation: 1063

Instead of setting search to null, you need to set it to an empty object. I'm not sure which JSON library you are using, but there should be an object constructor like new JsonObject(). Depending on what the allowed values for search are, you may also want to consider representing it in your class as Map<String, String> or something like that.

Upvotes: 3

Related Questions