java之读取json文件

导入maven包

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

        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.20</version>
            <scope>provided</scope>
        </dependency>
@Data
@ToString
public class Comment {
    
    

    private String tx_img;

    private String tx_name;

    private String content;

}

读取json文件

BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("src/main/resources/qs.json")));
        int line = 1;
        String context = null;
        String json = "";
        //json内容转化为Map集合通过遍历集合来进行封装
        while ((context = bufferedReader.readLine()) != null) {
    
    
            //Context就是读到的json数据
            json += context;
            line++;
        }
        System.out.println(json);

这样就获取到json字符串了

可以用

//json字符串转换为实体类对象

Comment comment = mapper.readValue(json, Comment.class);
//json字符串转换为列表对象
List<Comment> comments = Arrays.asList(mapper.readValue(json, Comment[].class));

实体类转换为json字符串

Comment comment = new Comment();
        comment.setTx_img("1.jpg");
        comment.setTx_name("李四");
        comment.setContent("一个小女孩");
        try {
    
    
            String jsonString = mapper.writeValueAsString(comment);
            System.out.println(jsonString);
            
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }

猜你喜欢

转载自blog.csdn.net/qq_42794826/article/details/108948430
今日推荐