I have an object that looks like this:
[
{
"title": "Job Title",
"email": "email@email.com",
"department": "Department",
"id": 123456789,
"name": "First Last"
}
]
How do I loop through this object and save the value of email in a variable?
Here is my code:
List<T> results = type.getResults();
String userEmail = "";
for (int i = 0; i < results.size(); i++) {
if (results.get(i).equals("email")) {
System.out.println("&&&&&&&&&&& in IF condition &&&&&&&&&&&&&&");
}
System.out.println(results.get(i));
}
But I just can't seem to get this loop to work.
Include jackson-core and jackson-databind libraries. Create a mapping object as below:
class User {
@JsonProperty
String id;
@JsonProperty
String title;
@JsonProperty
String email;
@JsonProperty
String department;
@JsonProperty
String name;
@Override
public String toString() {
return "User [id=" + id + ", email=" + email + "]";
}
}
Map the object as array as shown below:
ObjectMapper objectMapper=new ObjectMapper();
User[] users=objectMapper.readValue("[ { \"title\": \"Job Title\", \"email\": \"email@email.com\", \"department\": \"Department\", \"id\": 123456789, \"name\": \"First Last\" } ]", User[].class);
System.out.println(users[0]);
You can parse this json string to List.class
and then use typecasting for inner objects:
String json = "[{" +
"\"title\": \"Job Title\"," +
"\"email\": \"email@email.com\"," +
"\"department\": \"Department\"," +
"\"id\": 123456789," +
"\"name\": \"First Last\"" +
"}]";
List list = new ObjectMapper().readValue(json, List.class);
Map<String, Object> map = (Map<String, Object>) list.get(0);
Object email = map.get("email");
Object id = map.get("id");
System.out.println("email: " + email + ", id: " + id);
// email: email@email.com, id: 123456789
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.