0

I have an object that looks like this:

[
  {
    "title": "Job Title",
    "email": "[email protected]",
    "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.

3
  • That looks like normal JSON. Have you tried using a parser such as gson or jackson? Commented Feb 20, 2020 at 23:53
  • Is that not a JSON object? Commented Feb 20, 2020 at 23:53
  • Yes, I get this object from an API call. Commented Feb 20, 2020 at 23:54

2 Answers 2

1

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 protected]\", \"department\": \"Department\", \"id\": 123456789, \"name\": \"First Last\" } ]", User[].class);
        System.out.println(users[0]);
Sign up to request clarification or add additional context in comments.

Comments

0

You can parse this json string to List.class and then use typecasting for inner objects:

String json = "[{" +
        "\"title\": \"Job Title\"," +
        "\"email\": \"[email protected]\"," +
        "\"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 protected], id: 123456789

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.