简体   繁体   中英

Map JSON Response to Multiple POJO

I am sending response from in the form of JSON to a spring controller and I want to map it to a two different POJO. As it contains combined data for two pojo. How can i do it.

Code where I am sending JSON

$("#configure-buy-online").click(
        function(e) {
            var customProduct = '{"name":"Custom'
                + '","vcpu" : "'
                + $('#core')
                        .val()
                + '","ram" : "'
                + $('#ram')
                        .val()
                + '","hddSata":"'
                + $('#hddsata')
                        .val()
                + '"}';
            console.log("Product :"+ customProduct);
            $
            .ajax({
                type : 'POST',
                url : '../addToCartCustomize.do',
                dataType : 'json',
                contentType : 'application/json',
                data : customProduct,
                success : function(data) {
                    alert("Success");
                },
                error : function() {

                }
            });
        });

Spring Controller

String addCustomProductToCart(@RequestBody CustomProduct customProduct)
{

}

I know how to do it for One pojo. But dont know how to map same JSON to two Pojo.

I'm not aware of any JAX-RS or similar way of doing this. I would read in the JSON unmodified (as text) and use Jackson directly:

void doSomething(@RequestBody String pureJson) {
  ObjectMapper mapper = new ObjectMapper();  
  PojoA pojoA = mapper.readValue(pureJson, PojoA.class);
  PojoB pojoB = mapper.readValue(pureJson, PojoB.class);
}

Alternatively, you could turn PojoA into JSON and then into PojoB as follows:

void doSomething(@RequestBody PojoA pojoA) {
  ObjectMapper mapper = new ObjectMapper();  
  String pureJson = mapper.writeValueAsString(pojoA);
  PojoB pojoB = mapper.readValue(pureJson, PojoB.class);
}

But this is a bit more convoluted IMO.

You could wrap the 2 POJOs inside another POJO.

For example.

class PapaPojo {

  private BabyPojo1 babyPojo1;

  private BabyPojo2 babyPojo2;
}

Where BabyPojo1 and BabyPojo2 are your original 2 POJOs.

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