Java SimpleObjectIdResolver-class And Method Code Example


I apologize, but the SimpleObjectIdResolver is not a class from the Apache Commons IO library. It is a part of the Jackson JSON library, which is a separate library for handling JSON data.

SimpleObjectIdResolver class is a part of the Jackson databind package and it provides a simple implementation of ObjectIdResolver that can be used for deserializing JSON data with object references.

Here is an example of how to use the SimpleObjectIdResolver with Jackson JSON library:

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIdentityReference;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

public class Example {

    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
    @JsonDeserialize(as = AnimalImpl.class)
    @JsonSerialize(as = AnimalImpl.class)
    public interface Animal {
        String getName();
    }

    @JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@id")
    public static class AnimalImpl implements Animal {
        private String name;
        private int age;
        // getters and setters
    }

    public static class Zoo {
        @JsonIdentityReference(alwaysAsId = true)
        private Animal animal;
        // getters and setters
    }

    public static void main(String[] args) throws Exception {
        String json = "{\"animal\":{\"type\":\"Animal\",\"@id\":1,\"name\":\"Lion\",\"age\":5}}";

        ObjectMapper mapper = new ObjectMapper();
        mapper.setObjectIdResolver(new SimpleObjectIdResolver());
        Zoo zoo = mapper.readValue(json, Zoo.class);
        System.out.println("Animal : " + zoo.getAnimal().getName());
    }
}

In this example, Animal is a interface and AnimalImpl is an implementation of the interface.