zoukankan      html  css  js  c++  java
  • JSONObject和JSONArray(json-lib-2.4)的基本用法

    json-lib-2.4是一个用于JSON和java对象间转换的第三方包,其jar和依赖包下载地址在:https://files.cnblogs.com/files/xiandedanteng/json-lib-2.4%26dependencies_jars.rar

    下面列出了一些基本用法

    1.从对象到JSON

    1.1 单个对象的转化

    Piece p=pieceService.getPiece(id);                    
    String json=JSONObject.fromObject(p).toString();

    1.2 对象集合的转化

    List<?> ls=pieceService.listAllPieces(); // ls中元素是Piece对象           
    JSONArray jArray=JSONArray.fromObject(ls);        
    String json=jArray.toString();

    2.JSON到对象

    前台通过Ajax方式传json到后台比如像这样:

    $.ajax({
        url: url,// 请求的地址
        contentType: "application/json; charset=utf-8",
        data:{json:JSON.stringify(lines)},// 请求参数
        type:"get",// 请求方式
        dataType:"json",// 预期服务器返回的数据类型
        success: function(resp) {
        ......    
        },
        timeout: 50000,// 超时时间,超时后会调用error后的函数
        error: function(xhr, textStatus, errorThrown) {
        ......
        }
    });

    后台将这样得到前台送过来的参数:

    String jsonString=request.getParameter("json");

    而到的的jsonString是类似这样的: 

    [{"type":"in","pieceid":"6","count":"9","date":"09/05/2017"},{"type":"in","pieceid":"6","count":"9","date":"09/28/2017"},{"type":"in","pieceid":"6","count":"9","date":"09/28/2017"}]

    后台将JSON转化为对象可以这样:

    List<InoutLine> lines=new ArrayList<InoutLine>();
    String jsonString=request.getParameter("json");
    JSONArray json=JSONArray.fromObject(jsonString);
    JSONObject jsonOne;
    for(int i=0;i<json.size();i++){
      jsonOne = json.getJSONObject(i); 
      InoutLine line=new InoutLine();
      line.setType((String) jsonOne.get("type"));
      line.setPieceid((String) jsonOne.get("pieceid"));
      line.setCount((String) jsonOne.get("count"));
      line.setDate((String) jsonOne.get("date"));
      
      lines.add(line);
    }

    这样,JSON形式的字符串就变成Java里的对象了。 

    参考资料:

    1.Json字符串和java对象的互转  https://www.cnblogs.com/goloving/p/8361610.html

  • 相关阅读:
    html 知识
    mysql use mysql hang
    微信机器人 简化版
    Tk::Table
    好友消息和群消息区别
    完整的微信登陆 接收消息流程
    Python OOP知识积累
    Python OOP知识积累
    JSTL EL 详解
    JSP中的EL表达式详细介绍
  • 原文地址:https://www.cnblogs.com/heyang78/p/7610770.html
Copyright © 2011-2022 走看看