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!
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<User> userList = Arrays.asList(mapper.readValue(json, User[].class));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.