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

huangapple 未分类评论61阅读模式
英文:

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

问题

我已经编写了一些代码,将 List<Class> 的内容保存到一个 JSON 文件中,大致如下所示:

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

现在我尝试将此文件输入到我的程序中,程序可以工作,但只返回第一个 JSON 对象。这是我的代码:

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

我如何读取整个 JSON 文件,以及如何将其内容添加到上述相同的 List 中呢?每个教程等我遇到的都只解释如何使用单个对象。谢谢!

英文:

I have written some code which saves the contents of a List<Class> to a JSON file, which looks kinda like this:

{ "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. 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?
Every tutorial etc. I stumble upon only explains this using a single object.
Thank you!

答案1

得分: 0

可以这样做:

创建一个类似这样的用户类:

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

    // 设置器和获取器(Setters and getters)
}

现在你可以这样做:

String json = 你的Json字符串;
ObjectMapper mapper = new ObjectMapper();
User[] userArray = mapper.readValue(json, User[].class);
List<User> userList = Arrays.asList(mapper.readValue(json, User[].class));
英文:

You can do this:

Create a user class like this:

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&lt;User&gt; userList = Arrays.asList(mapper.readValue(json, User[].class));

huangapple
  • 本文由 发表于 2020年4月11日 08:57:50
  • 转载请务必保留本文链接:https://java.coder-hub.com/61150817.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定