package samples.jackson;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;

import java.io.IOException;

/**
 * @author Jitendra Singh.
 */
public class UserProfileDeserializer extends JsonDeserializer<UserProfile> {

    @Override
    public UserProfile deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        String EMPTY_STRING = "";

        JsonNode node = p.readValueAsTree();
        String name = node.has("name") ? node.get("name").asText() : EMPTY_STRING;
        String profilePic = node.has("profilePicture") ? node.get("profilePicture").asText() : EMPTY_STRING;
        String email = node.has("email") ? node.get("email").asText() : EMPTY_STRING;
        return new UserProfile(name, profilePic, email);
    }
}