• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

yxchun

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

读取JSON文件,并处理json数据(读取JSON中某个值)

需要处理的json文件

{
"code":200,
"message":"Success",
"data":{
    "fileName":"aa.jpg",
    "filePath":"file/aa.jpg",
    "base64":"AhCL95h014sgbqPbR9BtOiWgF5t8U2ggQZJqDwwEbScC/5B/QzHK9zqdrvZEXEPQ1"
    },
    "timestamp":229480701
}

1、使用fastjson,

  //fastjson,
    private static void readerMethod(String filePath) throws IOException {
        File file = new File(filePath);
        FileReader fileReader = new FileReader(file);
        Reader reader = new InputStreamReader(new FileInputStream(file), "Utf-8");
        int ch = 0;
        StringBuffer sb = new StringBuffer();
        while ((ch = reader.read()) != -1) {
            sb.append((char) ch);
        }
        fileReader.close();
        reader.close();
        String jsonStr = sb.toString();
        JSONObject jsonObject = JSON.parseObject(jsonStr);
 // 获取json key-value 值
        String data = jsonObject.getString("data");
        JSONObject parse = (JSONObject) JSONObject.parse(data);
        System.out.println(parse.getString("filePath"));
    }
需要maven依赖
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.21</version>
        </dependency>

2、jackson


    private static void toMap(String filePath) throws IOException {
        File file = new File(filePath);
        ObjectMapper objectMapper = new ObjectMapper();
        Map map = objectMapper.readValue(file, Map.class);
        System.out.println(map.get("code"));
    }
需要依赖
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.3</version>
        </dependency>

3、nio

    private static void nioMethod(String filePath) throws IOException {
        String jsonString = new String(Files.readAllBytes(Paths.get(filePath)));
        JSONObject obj = JSONObject.parseObject(jsonString);
        String data = obj.getString("data");
        JSONObject parse = (JSONObject) JSONObject.parse(data);
        String result=parse.getString("filePath");
    }

参考:https://blog.csdn.net/csdn_halon/article/details/120287992

posted on 2023-09-13 15:27  yxchun  阅读(39)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3