编写接口返回JSON类型数据

1、完成一个需求,需要返回JSON类型数据,我是使用JSONArray.fromObject()方法获取json数据,然后直接返回字符串。
方法头加上@Produces(MediaType.APPLICATION_JSON)注解来指定返回JSON数据

2、代码如下:

    @GET
    @Path("getGoodsSellerArrayList")
    @Produces(MediaType.APPLICATION_JSON)
    public String getGoodsSellerArrayList(
            @QueryParam("projectId") String projectId,
            @QueryParam("moduleType") String moduleType) {

        Map mapResult = null;
        List> listResult = new ArrayList>();
        try {
            //商品模块的项目定义
            List defineList = this.tbgProjectDefineService
                    .findAllByProjectAndModuleType(Long.parseLong(projectId),
                            Integer.valueOf(moduleType));
            StringBuffer sb = new StringBuffer("");
            StringBuffer str = new StringBuffer("");

            for (TbgProjectDefine tbgProjectDefine : defineList) {
                if (tbgProjectDefine.getTbgGoodsModule() != null
                        && tbgProjectDefine.getTbgGoodsModule()
                                .getTbgGoodsCategory() != null) {
                    //商品分类表
                    TbgGoodsCategory category = tbgProjectDefine
                            .getTbgGoodsModule().getTbgGoodsCategory();
                    str.append(category.getGcId()).append(",");
                    sb.append(category.getParentId()).append(",");

                }
            }
            //获取二级分类下的商家信息
            if(StringUtils.isNotEmpty(str.toString()))
            {
                //获取商家id和parentId
                List list = this.tbgProjectDefineService.getList(str.toString());
                for(Object[] obj : list)
                {
                    String sellerId = String.valueOf(obj[0]);
                    String parentId = String.valueOf(obj[1]);
                    CrmManageSeller cSeller = this.crmManageSellerService.findSellerById(Long.valueOf(sellerId));

                    TbgGoodsFile logoFile = new TbgGoodsFile();
                    //获取logo信息      
                    //type:4,商家;rectId:关联id
                    Map map = LittleUtils.getMap("type",4,"rectId",sellerId);

                    //查询商家的logo信息
                    List logoFiles = tbgGoodsFileService.findAll(map);

                    if(logoFiles.size() > 0)
                    {
                        logoFile = logoFiles.get(0);

                    }

                    mapResult = new HashMap();
                    mapResult.put("sellerId", sellerId);
                    mapResult.put("parentId", parentId);
                    mapResult.put("clientShow", "1");
                    mapResult.put("address", cSeller.getAddress());
                    mapResult.put("name", cSeller.getSellerName());
                    mapResult.put("phone", cSeller.getTelNo());
                    mapResult.put("logoFilePath", logoFile.getFilePath());

                    listResult.add(mapResult);
                }
            }
            //获取一级分类下商品分类信息
            if (StringUtils.isNotEmpty(sb.toString())) {
                List list = this.tbgProjectDefineService
                        .findCategoryByLevel(sb.toString());
                for (TbgGoodsCategory tg : list) {

                        mapResult = new HashMap();
                        mapResult.put("gcId", tg.getGcId().toString());
                        mapResult.put("gcName", tg.getGcName());
                        mapResult.put("clientShow", "0");
                        //mapResult.put("parentId", -1l);

                        listResult.add(mapResult);
                }
            }

            JSONArray jsonArray = JSONArray.fromObject(listResult);

            return jsonArray.toString();
        } catch (Exception e) {
            logger.info("获取商家信息失败");
            e.printStackTrace();
        }

        return null;
    }

3、下面加上网上找的javaBean,Map,List转json格式总结:

 public class User {  

    private String username;  
    private String password;  

    public String getUsername() {  
        return username;  
    }  
    public void setUsername(String username) {  
        this.username = username;  
    }  
    public String getPassword() {  
        return password;  
    }  
    public void setPassword(String password) {  
        this.password = password;  
    }  

} 

普通JavaBean转为Json格式

1、转成JsonArray格式

User user = new User();
user.setUserName("test");
user.setPassword("123");
JSONArray json = JSONArray.fromObject(user);
System.out.println(json);[{"password":"123","username":"test"}] 
response.getWriter().print(json.toString());

在js文件中去取数据:

$.getJSON("http://localhost:8080/jQueryDemo/servlet/UserServlet",null,function(data) { 
      alert(data[0].username); 
      alert(data[0].password); 
}); 

2、转成JSONObject类型

JSONObject jsonObj = JSONObject.fromObject(user);
System.out.println(jsonObj);//{"password":"1234","username":"cxl"} 
response.getWriter().print(jsonObj);

在js文件取数据:
alert(data.userName);
alert(data.password);

List转成JSON格式

List users = new ArrayList(); 
User user = new User(); 
user.setUsername("cxl"); 
user.setPassword("1234"); 
User u = new User(); 
u.setUsername("lhl"); 
u.setPassword("1234"); 
users.add(user); 
users.add(u); 

1、转成JSONArray类型

JSONArray json = JSONArray.fromObject(users);
System.out.println(json.toString());
//[{"password":"1234","username":"cxl"},{"password":"1234","username":"lhl"}] 
response.getWriter().print(json.toString()); 

js中取数据:

alert(data[0].username);

2、转成JSONObject类型
不可直接使用JSONObject jsonObj = JSONObject.fromObject(users);
可通过下列方式

JSONObject jsonObj = new JSONObject(); 
jsonObj.put("users", users); 
jsonObj.put("u", u); 
System.out.println(jsonObj); 
{"users":[{"password":"1234","username":"cxl"},{"password":"1234","username":"lhl"}], 
  "u":{"password":"1234","username":"lhl"}} 
response.getWriter().print(jsonObj); 

js中取数据:

alert(data.users[0].username); 
alert(data.u[0].username);

Map转成json格式

Map<String,Object> map = new HashMap<String,Object>(); 
map.put("users", users); 
map.put("u", u); 

1、转成JSONArray类型

JSONArray json = JSONArray.fromObject(map); 
System.out.println(json.toString());// 
[{"users":[{"password":"1234","username":"cxl"},{"password":"1234","username":"lhl"}],"u":{"password":"1234","username":"lhl"}}] 
response.getWriter().print(json.toString); 

js中取数据:

alert(data[0].users[0].username); 

2、转成JSONObject类型

JSONObject json = JSONObject.fromObject(map); 
System.out.println(json);// 
{"user":[{"password":"1234","username":"cxl"},{"password":"1234","username":"lhl"}],"u":{"password":"1234","username":"lhl"}} 
response.getWriter().print(json); 

js中取数据:

alert(data.user[0].username); 

以上

你可能感兴趣的:(编写接口返回JSON类型数据)