简体   繁体   English

如何使用 Jackson 读取 JSON 文件中的多个对象?

[英]How to read multiple objects in a JSON file with Jackson?

I have written some code which saves the contents of a List<Class> to a JSON file, which looks kinda like this:我编写了一些代码,将List<Class>的内容保存到 JSON 文件中,看起来有点像这样:

{ "firstName": "Name", "lastName": "LastName", "Email": "Email" } { "firstName": "Name2", "lastName": "LastName2", "Email": "Email2" }

Now I'm trying to input this file into my program, which works but only the first JSON Object is being returned.现在我正在尝试将此文件输入到我的程序中,该程序有效,但仅返回第一个 JSON Object。 This is my code:这是我的代码:

ObjectMapper mapper = new ObjectMapper();
JsonNode readFile = mapper.readTree(new File("path/to/file.json"));

How can I read the full JSON file and how can I add the contents of it to the same List mentioned above?如何阅读完整的 JSON 文件,如何将其内容添加到上述相同列表中? Every tutorial etc. I stumble upon only explains this using a single object.我偶然发现的每个教程等都只使用单个 object 来解释这一点。 Thank you!谢谢!

You can do this:你可以这样做:

Create a user class like this:像这样创建一个用户 class :

public class User {
    private String email;
    private String firstName;
    private String lastName;

    // Setters and getters
}

Now you can do this:现在你可以这样做:

String json = yourJson;
ObjectMapper mapper = new ObjectMapper();
User[] userArray = mapper.readValue(json, User[].class);
List<User> userList = Arrays.asList(mapper.readValue(json, User[].class));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM