简体   繁体   English

从Java Restful API按预期获取JSON格式的数据

[英]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. 我有下面的宁静的api代码,它返回json数据。

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. 我建议您使用JSON API并使用它传递DTO对象。 You need to define a DTO class such as: 您需要定义一个DTO类,例如:

    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. 将此类转换为JSON并返回它可以解决您的问题。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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