简体   繁体   中英

Get Data in JSON Format as expected from a Java Restful API

The output now is:

{
 "Product_Type":
    "[{\"active\":true,\"description\":\"ALL IN ONES\",\"id\":2},     
      {\"active\":true,\"description\":\"ACCESSORIES\",\"id\":1}]",
 "Product_Brand":
    "[{\"active\":false,\"brand\":\"101 DALMATIANS\",\"id\":1}]"
}

Expected is:

{
 "Product_Type":
    [{"active":true,"description":"ALL IN ONES","id":2},     
      {"active":true,"description":"ACCESSORIES","id":1}],
 "Product_Brand":
    [{"active":false,"brand":"101 DALMATIANS","id":1}]"
}

I have the below restful api code which returns json data.

Code:
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("brand")
public String getProductBrand() {       
    return attributeMasterService.getProductBrand() + 
            attributeMasterService.getProductType();        
}   

Output:

[{"active":false,"brand":"101 DALMATIANS","id":1}]      
[{"active":true,"description":"ACCESSORIES","id":1},     
{"active":true,"description":"ALL IN ONES","id":2}]

I need help in getting the data in a format mentioned below.

Basically I need to append the document names to the arrays.

[
Product_Brand:
[    {"active":false,"brand":"101 DALMATIANS","id":1}],
Product_Type:
[    {"active":true,"description":"ALL IN ONES","id":2},     
     {"active":true,"description":"ACCESSORIES","id":1}]
]  

Could you please help me in building the result as above?

Thanks,

I recommend you to use a JSON API and pass your DTO objects by using it. You need to define a DTO class such as:

    public class A { 
        List<ProductBrand> brands; 
        List<ProductType> types; 

        //getter and setter methods
    }

and then create an instance of this one and set its fields. Converting this class to JSON and returning it would solve your problem.

Use this.

JSONObject json1 = new JSONObject();
json1.put("Product_Brand", attributeMasterService.getProductBrand());
json1.put("Product_Type", attributeMasterService.getProductType());
return json1.toString();

Try this.

JSONObject json1 = new JSONObject();
ObjectMapper mapper = new ObjectMapper();
String jsonInString = mapper.writeValueAsString(attributeMasterService.getProductBrand());
String jsonInString1 = mapper.writeValueAsString(attributeMasterService.getProductType());
JSONParser parser = new JSONParser();
JSONArray json = (JSONArray) parser.parse(jsonInString);
JSONArray json2 = (JSONArray) parser.parse(jsonInString1);
json1.put("Product_Brand", json);
json1.put("Product_Type", json2);
return json1;

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