POST / PUT期间所有对象的单个自定义反序列化器作为其ID或嵌入的整个对象

时间:2017-10-06 09:55:21

标签: json spring jackson spring-data spring-data-jpa

@Entity
public Product {
   @Id
   public int id;

   public String name;

   @ManyToOne(cascade = {CascadeType.DETACH} )
   Category category

   @ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.DETACH} )
   Set<Category> secondaryCategories;


}

和这个实体:

@Entity
public Category {
   @Id
   public int id;

   public String name;
}

我希望能够使用json发送POST

来自客户端的

{ name: "name", category: 2, secondaryCategories: [3,4,5] }

并且可以像:

一样反序列化
{ name: "name", category: {id: 2 }, secondaryCategories: [{id: 3}, {id: 4}, {id: 5}] }

如果它是作为

发送的
 { name: "name", category: {id: 2 }, secondaryCategories: [{id: 3}, {id: 4}, {id: 5}] }

我希望它仍能像现在一样工作

我需要什么样的注释和自定义解串器?希望反序列化器可以用于所有可能具有id作为属性的对象

谢谢!

修改

3 个答案:

答案 0 :(得分:2)

另一种方法是使用@JsonCreator工厂方法,如果您可以修改您的实体

private class Product {
    @JsonProperty("category")
    private Category category;

    @JsonProperty("secondaryCategories")
    private List<Category> secondaryCategories;
}


private class Category {
    @JsonProperty("id")
    private int id;

    @JsonCreator
    public static Category factory(int id){
        Category p = new Category();
        p.id = id;
        // or some db call 
        return p;
    }
}

甚至这样的事情也应该起作用

private class Category {
    private int id;

    public Category() {}

    @JsonCreator
    public Category(int id) {
        this.id = id;
    }
}

答案 1 :(得分:1)

您可以尝试多种选项,实际上自定义反序列化器/序列化器可能有意义,但您也可以使用@JsonIdentityInfo(反序列化)+ @JsonIdentityReference来实现此目的(如果需要序列化为整数) )注释。

反序列化

Work both for 
{ "category":1 }
{ "category":{ "id":1 }

因此,您需要使用@JsonIdentityInfo

注释可以通过其ID进行反序列化的每个类
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
        property = "id", 
        scope = Product.class,  // different for each class
        resolver = MyObjectIdResolver.class)

这里的难点在于您实际上必须编写可以解析数据库/其他来源中的对象的自定义ObjectIdResolver。请看下面示例中的MyObjectIdResolver.resolveId方法中的简单反射版本:

private static class MyObjectIdResolver implements ObjectIdResolver {
    private Map<ObjectIdGenerator.IdKey,Object> _items  = new HashMap<>();

    @Override
    public void bindItem(ObjectIdGenerator.IdKey id, Object pojo) {
        if (!_items.containsKey(id)) _items.put(id, pojo);
    }

    @Override
    public Object resolveId(ObjectIdGenerator.IdKey id) {
        Object object = _items.get(id);
        return object == null ? getById(id) : object;
    }

    protected Object getById(ObjectIdGenerator.IdKey id){
        Object object = null;
        try {
            // todo objectRepository.getById(idKey.key, idKey.scope)
            object = id.scope.getConstructor().newInstance(); // create instance
            id.scope.getField("id").set(object, id.key);  // set id
            bindItem(id, object);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }

    @Override
    public ObjectIdResolver newForDeserialization(Object context) {
        return this;
    }

    @Override
    public boolean canUseFor(ObjectIdResolver resolverType) {
        return resolverType.getClass() == getClass();
    }
}

序列化

Default behavior
{ "category":{ "id":1 , "name":null} , secondaryCategories: [1 , { { "id":2 , "name":null} ]}

此处描述了默认行为:https://github.com/FasterXML/jackson-databind/issues/372 并将生成第一个元素的对象和后面每个元素的id。杰克逊中的ID /引用机制可以使对象实例只被完全序列化一次并在其他地方通过其ID引用。

选项1.(始终为id)

Works for 
{ "category":1 , secondaryCategories:[1 , 2]}

需要在每个对象字段上方使用@JsonIdentityReference(alwaysAsId = true)(可以在页面底部的演示中取消注释)

选项2.(始终作为完整对象表示)

Works for 
{ "category" : { "id":1 , "name":null} , secondaryCategories: [{ "id":1 , "name":null} , { "id":2 , "name":null}]}

此选项很棘手,因为您必须以某种方式删除序列化的所有IdentityInfo。一个选项可能是拥有2个对象映射器。 1用于序列化,2用于反序列化并配置某种mixin或@JsonView

更容易实现的另一种方法是使用SerializationConfig完全忽略@JsonIdentityInfo注释

@Bean
public ObjectMapper objectMapper() {
    ObjectMapper mapper = new ObjectMapper();

    SerializationConfig config = mapper.getSerializationConfig()
            .with(new JacksonAnnotationIntrospector() {
        @Override
        public ObjectIdInfo findObjectIdInfo(final Annotated ann) {
            return null;
        }
    });

    mapper.setConfig(config);

    return mapper;
}

可能更好的方法是以相同的方式为deserializerconfig实际定义@JsonIdentityInfo并删除类上面的所有注释。像this

这样的东西

此时您可能希望您刚编写自定义序列化程序/反序列化程序

这是工作(没有春天的简单杰克逊)演示:

import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;

public class Main {

    @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
            property = "id",
            resolver = MyObjectIdResolver.class,
            scope = Category.class)
    public static class Category {
        @JsonProperty("id")
        public int id;
        @JsonProperty("name")
        public String name;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        @Override
        public String toString() {
            return "Category{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }

    @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
            property = "id",
            resolver = MyObjectIdResolver.class,
            scope = Product.class)
    public static class Product {
        @JsonProperty("id")
        public int id;
        @JsonProperty("name")
        public String name;

        // Need @JsonIdentityReference only if you want the serialization
        // @JsonIdentityReference(alwaysAsId = true)
        @JsonProperty("category")
        Category category;

        // Need @JsonIdentityReference only if you want the serialization
        // @JsonIdentityReference(alwaysAsId = true)
        @JsonProperty("secondaryCategories")
        Set<Category> secondaryCategories;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        @Override
        public String toString() {
            return "Product{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", category=" + category +
                    ", secondaryCategories=" + secondaryCategories +
                    '}';
        }
    }

    private static class MyObjectIdResolver implements ObjectIdResolver {

       private Map<ObjectIdGenerator.IdKey,Object> _items;

        @Override
        public void bindItem(ObjectIdGenerator.IdKey id, Object pojo) {
            if (_items == null) {
                _items = new HashMap<ObjectIdGenerator.IdKey,Object>();
            } if (!_items.containsKey(id))
                _items.put(id, pojo);
        }

        @Override
        public Object resolveId(ObjectIdGenerator.IdKey id) {
            Object object = (_items == null) ? null : _items.get(id);
            if (object == null) {
                try {

                    // create instance
                    Constructor<?> ctor = id.scope.getConstructor();
                    object = ctor.newInstance();

                    // set id
                    Method setId = id.scope.getDeclaredMethod("setId", int.class);
                    setId.invoke(object, id.key);
                    // https://github.com/FasterXML/jackson-databind/issues/372
                    // bindItem(id, object); results in strange behavior

                } catch (NoSuchMethodException | IllegalAccessException
                        | InstantiationException | InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
            return object;
        }

        @Override
        public ObjectIdResolver newForDeserialization(Object context) {
            return new MyObjectIdResolver();
        }

        @Override
        public boolean canUseFor(ObjectIdResolver resolverType) {
            return resolverType.getClass() == getClass();
        }
    }

    public static void main(String[] args) throws Exception {
        String str = "{ \"name\": \"name\", \"category\": {\"id\": 2 }, " +
                "\"secondaryCategories\":[{\"id\":3},{\"id\":4},{\"id\":5}]}";

        // from  str
        Product product = new ObjectMapper().readValue(str, Product.class);
        System.out.println(product);

        // to json
        String productStr = new ObjectMapper().writeValueAsString(product);
        System.out.println(productStr);

        String str2 = "{ \"name\": \"name\", \"category\":  2, " +
                "\"secondaryCategories\": [ 3,  4,  5] }";

        // from  str2
        Product product2 = new ObjectMapper().readValue(str2, Product.class);
        System.out.println(product2);

        // to json
        String productStr2 = new ObjectMapper().writeValueAsString(product2);
        System.out.println(productStr2);
    }
}

答案 2 :(得分:0)

经过多次努力之后的完整解决方案 - 感谢https://stackoverflow.com/users/1032167/varren的评论和https://stackoverflow.com/a/16825934/986160我能够在{{1}中使用默认的反序列化(通过本地新的objectMapper)没有这个答案中的障碍:https://stackoverflow.com/a/18405958/986160

代码尝试解析一个int,如果它是一个整个对象,它只是传递它 - 所以它仍然有效,例如当你发出StdDeserializer的POST / PUT请求时,或者换句话说当{ {1}}未嵌入

Category

对于我需要表达的每个实体,我需要在Spring Boot应用程序的全局ObjectMapper Bean中配置它:

Category

这是来自https://stackoverflow.com/a/14374995/986160

的ReflectionUtils
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import org.springframework.context.annotation.Bean;

import java.io.IOException;

public class IdWrapperDeserializer<T> extends StdDeserializer<T> {

    private Class<T> clazz;

    public IdWrapperDeserializer(Class<T> clazz) {
        super(clazz);
        this.clazz = clazz;
    }

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
        mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
        return mapper;
    }

    @Override
    public T deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException {
        String json = jp.readValueAsTree().toString();

        T obj = null;
        int id = 0;
        try {
            id = Integer.parseInt(json);
        }
        catch( Exception e) {
            obj = objectMapper().readValue(json, clazz);
            return obj;
        }
        try {
            obj = clazz.newInstance();
            ReflectionUtils.set(obj,"id",id);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return obj;
    }

}