简体   繁体   中英

input request framing in rest api

I'm writing logic for framing the input request body which needs to be sent when calling the Rest API. I'm using Map for doing it so and then using object mapper i'm converting into string which will be of json format.

Example: Sample input request body

{ "A":{"1":"aa","2":"bb" },"B":{"3":"cc","4":"dd"}}

My code will look like this

MyReq req=new MyReq();
Map<String, String> A = Maps.newHashMap();
 A.put("1","aa");
A.put("2","bb");
Map<String, String> B = Maps.newHashMap();
B.put("3","cc");
B.put("4","dd");
 req.setA(A);
req.setB(B);
final ObjectMapper obj = new ObjectMapper();
 String myjson=obj.writeValueAsString(req);

But , in case of this format, how can i do it,

{"A":{"1":"aa","2":"bb"},"B":{"New":{"new1":"qq","new2","zz",},"3":"cc","4":"dd"}}

The maps you are using and the base object of the response represent simple JSON objects (as opposed to arrays, ...). You have many choices to create the response you are describing. To expand your example, in JAXB you could do the following:

@XMLRootElement
public class MyReq {
    ....
    @XmlElement(name = "3")
    private String three;

But do not do this in the case of non descriptive properties such as 3 Use JAXB if the response is clearly defined and used frequently and/or if the JAXB classes are used in other parts of the application (JPA beans, ...).

You can also replace the class MyRec using a Map<String,Object> and simply put the other maps in as well as the other values put("3","cc") .

Ok take also a look at the JSON-P API which is the best solution for such a random example:

JsonObject response = Json.createObjectBuilder()
    .add("A", Json.createObjectBuilder().add("1", "aa").add("2", "bb"))
    .add("B", Json.createObjectBuilder().add("NEW", Json.createObjectBuilder().add("new1", "qq").add("new2", "zz")))
    .add("3", "cc")
    .add("4", "dd").build();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM