小编典典

使用杰克逊将列表转换为json

json

使用以下代码,我已将列表转换为json,但格式如下:

{"GodownMaster":[{"pname":"FCI CHARLAPALLI","pcode":"16042"},
{"pname":"MLS CIRCLE 1 L.B. NAGAR","pcode":"16016"},{"pname":"MLS CIRCLE 4 
AZAMABAD","pcode":"16003"},{"pname":"MLS CIRCLE 6 
VIDYANAGAR","pcode":"16005"},{"pname":"OTHERS","pcode":"1699"}]}

但我想将其转换为:

[{"pname":"FCI CHARLAPALLI","pcode":"16042"},
{"pname":"MLS CIRCLE 1 L.B. NAGAR","pcode":"16016"},{"pname":"MLS CIRCLE 4 
AZAMABAD","pcode":"16003"},{"pname":"MLS CIRCLE 6 
VIDYANAGAR","pcode":"16005"},{"pname":"OTHERS","pcode":"1699"}]

以下是我的弹簧控制器:

@RequestMapping("/getGodowns")
public @ResponseBody Map 
getGodownsBasedOnDistrict(@RequestParam(value="district_code") String 
dist_code) {

List<CscGodownBean> godown_list = null;
Map<String, List<CscGodownBean>> m = new HashMap();
String exception = null;
try
{
//getting name and codes here
godown_list = scm_service.getGodownListBesedOnDistCode(dist_code);
}catch(Exception ex)
{
ex.printStackTrace();
exception = ex.getMessage();
}

if(godown_list!=null) {
for(int i=0;i<godown_list.size();i++) {
m.put("GodownMaster",godown_list);
}
}
return m;
}

阅读 45

收藏
2020-07-27

共1个答案

小编典典

更改从返回结果MapList<CscGodownBean>放:retrun godown_list 如此;

@RequestMapping("/getGodowns")
public @ResponseBody List<CscGodownBean>
getGodownsBasedOnDistrict(@RequestParam(value="district_code") String 
dist_code) {

List<CscGodownBean> godown_list = new ArrayList<CscGodownBean>();
String exception = null;
try
{
    //getting name and codes here
    godown_list = scm_service.getGodownListBesedOnDistCode(dist_code);
}catch(Exception ex)
{
   ex.printStackTrace();
   exception = ex.getMessage();
}

return godown_list ;
}

更新

您可以将结果作为字符串返回,您将获得所需的内容:

@RequestMapping("/getGodowns")
public @ResponseBody String
getGodownsBasedOnDistrict(@RequestParam(value="district_code") String 
dist_code) {

List<CscGodownBean> godown_list = new ArrayList<CscGodownBean>();
String exception = null;
try
{
    //getting name and codes here
    godown_list = scm_service.getGodownListBesedOnDistCode(dist_code);
}catch(Exception ex)
{
   ex.printStackTrace();
   exception = ex.getMessage();
}
ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    String arrayToJson = objectMapper.writeValueAsString(godown_list);
    System.out.println("Convert List to JSON :");
    System.out.println(arrayToJson);

return arrayToJson ;
}

返回的字符串是json格式。

2020-07-27