使用杰克逊将列表转换为json [英] convert list to json using Jackson

查看:99
本文介绍了使用杰克逊将列表转换为json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
}

推荐答案

将返回结果从Map更改为List<CscGodownBean>并放置:retrun godown_list 所以;

Change the return result from Map to List<CscGodownBean> and put : retrun godown_list So;

@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 ;
}

更新

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

And you can return result as string and you will get what you need :

@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格式.

The returned String is json format.

这篇关于使用杰克逊将列表转换为json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆