Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

spring - convert list to json using Jackson

With the below code I have converted list to json but the format is as follows:

{"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"}]} 

but I want to convert it as :

[{"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"}] 

Below is my spring controller :

@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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Why are you putting your list into Map? Code looks weird. If you want to return a list, just do it:

@RequestMapping("/getGodowns")
public @ResponseBody List<CscGodownBean> getGodownsBasedOnDistrict(@RequestParam(value="district_code") String dist_code) {
    List<CscGodownBean> godown_list = null;
    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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...