zoukankan      html  css  js  c++  java
  • 前端_json格式转换

    通俗JavaBean(以User为例)转成json格局
    1.转成JSONArray类型
    User user = new User();
    user.setUsername("cxl");
    user.setPassword("1234");
    JSONArray json = JSONArray.Object(user);
    System.out.println(json);//[{"password":"1234","username":"cxl"}]
    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.Object(user);
    System.out.println(jsonObj);//{"password":"1234","username":"cxl"}
    response.getWriter().print(jsonObj);
    在js文件取数据
    alert(data.username);
    alert(data.password);
    
    List转成json格局
    List<User> users = new ArrayList<User>();
    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.Object(users);
    System.out.println(json.toString());
    //[{"password":"1234","username":"cxl"},{"password":"1234","username":"lhl"}]
    response.getWriter().print(json.toString());
    js中取数据:alert(alert(data[0].username));
    2.转成JSONObject类型
    不成直接应用JSONObject jsonObj = JSONObject.Object(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.Object(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.Object(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); 
  • 相关阅读:
    Redis的发布订阅
    Redis的事务
    Redis的持久化下
    Redis的持久化上
    Redis数据类型之Redis有序集合Zset(sorted set
    Redis数据类型之Redis哈希(Hash)
    Redis数据类型之Redis集合(Set)
    LeetCode#53-最大子序和
    LeetCode#442-数组中的重复数据
    LeetCode#1014-最佳观光组合
  • 原文地址:https://www.cnblogs.com/logep/p/3552317.html
Copyright © 2011-2022 走看看