美文网首页
JSON常用方式

JSON常用方式

作者: 缘木与鱼 | 来源:发表于2019-11-21 17:51 被阅读0次

    JSONObject的jar包依赖

    <dependency>
          <groupId>net.sf.json-lib</groupId>
          <artifactId>json-lib</artifactId>
          <version>2.4</version>
          <classifier>jdk15</classifier>
    </dependency>
    

    map、string、json互转

    // 创建Map
    Map<String,Object> map=new HashMap<String,Object>();
    map.put("fff","fff");
    System.out.println(map.toString());
    // 将Map转换成JSON
    JSONObject jsonObject=JSONObject.fromObject(map);
    // 转换成String
    System.out.println(jsonObject.toString());
    
    String 转Json
    JSONObject  jasonObject = JSONObject.fromObject(str);
    
    String 转Map
    JSONObject  jasonObject = JSONObject.fromObject(str);
    Map map = (Map)jasonObject;
    

    String、JSONArray 与 List互转

    public static void main(String[] args) {
        // 获取json字符串
        String json = "[{'CustFateWay1':'lee','password':'1123'}, {'CustFateWay2':'lee','password':'2123'}, {'CustFateWay3':'lee','password':'3123'}]";
        // 将json字符串转换为json数组(JSONArray)
        JSONArray jsonArray1 = JSONArray.fromObject(json);
        // 将json数组转换成list
        List<JSONObject> list = jsonArray1;
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i).toString());
        }
        // 获取json数组的长度
        int leng = jsonArray1.size();
        // 循环遍历取出json数组中的json对象
        for (int i = 0; i < leng; i++){
                // 获取json的对象
            JSONObject json1 = (JSONObject) jsonArray1.get(i);
                // 获取json对象中的内容
            String str = json1.getString("password");
            System.out.println(str);
        }
    }
    

    相关文章

      网友评论

          本文标题:JSON常用方式

          本文链接:https://www.haomeiwen.com/subject/mfgtwctx.html