0

Similar question might be asked before on here, but I had no luck and I was wondering how to extract specific objects like user in from below json string and then construct an ArrayList. However, there is one twist, one of the property directly under Users is a random number, which can be anything!!!

Here is how my json string looks like:

<code>{
    "_links": {
    },
    "count": {
    },
    "users": {
        "123321": { //*Is a random number which can be any number
            "_links": {
            },
            "user": {
                "id": "123321",
                "name": "...",
                "age": "...",
                "address": ""
                ..
            }
        },
        "456654": {
            "_links": {
            },
            "user": {
                "id": "456654",
                "name": "...",
                "age": "...",
                "address": ""
                ...
            }
        }
        ...
    },
    "page": {
    }
}
</code>

The java object I would like to transform it to is:

@JsonIgnoreProperties(ignoreUnknown = true) // Ignore any properties not bound here
public class User {
    private String id;
    private String name;
    //setter:getter
}

Note: The transformation should only consider those two fields (id,name), and ignore the rest of the fields from the json response user:{} object.

Ideally, I would like to end up with a list like this:

List<User> users = resulted json transformation should return a list of users!!

Any idea how can I do this please ideally with Jackson JSON Parser/ or maybe GSON?

dllhell
  • 1,987
  • 3
  • 34
  • 51
Simple-Solution
  • 4,209
  • 12
  • 47
  • 66

2 Answers2

1

Since the user keys are random, you obviously can't map them to a named Java field. Instead, you can parse the top-level object as a map and the manually pull out the user objects.

public class UserWrapper {
    private User user;
    public User getUser() { return user; }
}

public class Root {
    private Map<String, UserWrapper> users;

    public List<User> getUsers() {
        List<User> usersList = new ArrayList();
        for (String key : map.keySet()) {
            UserWrapper wrapper = map.get(key);
            usersList.add(wrapper.getUser());
        }

        return userList;
    }
}

Root root = parseJson();
List<User> users = root.getUsers()

Hope that helps!

dominicoder
  • 9,338
  • 1
  • 26
  • 32
0

jolt transformer is your friend. Use shift with wildcard * to capture arbitrary node value and then standard mappers (Jackson /gson) .

Alexander.Furer
  • 1,817
  • 1
  • 16
  • 24