Vaan
Vaan

Reputation: 21

How to convert references into instances during JSON deserialization

This was a question, but it has been solved. I was trying to do deserialize some JSON data into Java POJO's. For example take the following JSON data:

For the Account data i have the following JSON data which refers to users by their id:

{
  "name" : "Bob's Account",
  "roles": {
    "administrator" : "user-1",
    "owner"         : "user-1",
    "participant"   : "user-2" 
  }
}

And for the Users 'Bob' and 'Alice' i've got this JSON data:

{
  "name": "Bob",
  "id"  : "user-1"
}
{
  "name": "Alice",
  "id"  : "user-2"
}

What i'd wanted to achieve is to deserialize the data into the following Java classes:

import java.util.Map;
import java.util.HashMap;

public class Account {
  String name;
  Map<String, User> roles = new HashMap<>();
}

and

public class User {
  String id;
  String name;
}

Notice that the Account class has a map that links String to a User instance.

Upvotes: 0

Views: 156

Answers (1)

Vaan
Vaan

Reputation: 21

To do this you must annotate the property roles in the the Account object as follows:

  ⋯snip⋯
  @JsonDeserialize(contentConverter = UserReferenceConverter.class)
  Map<String, User> roles = new HashMap<>();
  ⋯snip⋯

And then with create a UserReferenceConverter that can convert a user-id in the form of a String into an actual User instanceenter code here:

public class UserReferenceConverter extends StdConverter<String, User> {
  
  @Override
  public User convert( String value ) {
    // Get the user...
    return UserRepository.getUserById( value );
  }
}

To load the Account from a JSON string run this:

import com.fasterxml.jackson.databind.ObjectMapper;

  ⋯snip⋯
  ObjectMapper mapper = new ObjectMapper();
  Account account = mapper.readValue(json, Account.class);
  ⋯snip⋯

Upvotes: 1

Related Questions