当前位置: 首页 > 知识库问答 >
问题:

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

空英达
2023-03-14
@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的帖子

<代码>{名称:“名称”,类别:2,次要类别:[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为属性的对象

谢啦!

编辑

  • 查看首选zafrost的@JsonCreator答案(https://stackoverflow.com/a/46618366/986160)
  • 请参阅我的完整答案(https://stackoverflow.com/a/46618193/986160),用于扩展StdDeserializer并通过ObjectMapper
  • 使用默认反序列化

共有3个答案

严安志
2023-03-14

经过多次斗争,最终的解决方案是https://stackoverflow.com/users/1032167/varren的评论和https://stackoverflow.com/a/16825934/986160我能够在StdDeserializer中使用默认的反序列化(通过一个本地新的objectMapper),而没有这个答案中的障碍:https://stackoverflow.com/a/18405958/986160

代码试图解析一个int,如果它是一个完整的对象,它只会将其传递出去,因此它仍然可以工作,例如,当您对一个类别发出POST/PUT请求时,或者换句话说,当没有嵌入类别时

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;
    }

}

对于我需要按照所述方式操作的每个实体,我需要在Spring Boot应用程序的全局ObjectMapper Bean中对其进行配置:

@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);

    SimpleModule testModule = new SimpleModule("MyModule")
            .addDeserializer(Category.class, new IdWrapperDeserializer(Category.class))

    mapper.registerModule(testModule);

    return mapper;
}

这是我的https://stackoverflow.com/a/14374995/986160

public class ReflectionUtils {
    // 
    public static boolean set(Object object, String fieldName, Object fieldValue) {
        Class<?> clazz = object.getClass();
        while (clazz != null) {
            try {
                Field field = clazz.getDeclaredField(fieldName);
                field.setAccessible(true);
                field.set(object, fieldValue);
                return true;
            } catch (NoSuchFieldException e) {
                clazz = clazz.getSuperclass();
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }
        }
        return false;
    }
}
伯鸿达
2023-03-14

您可以尝试几个选项,实际上自定义反序列化器/序列化器可能会有意义,但您也可以通过注释(用于反序列化)来实现这一点。

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

因此,您需要使用jsonidentialinfo对每个可以从其id反序列化的类进行注释

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
        property = "id", 
        scope = Product.class,  // different for each class
        resolver = MyObjectIdResolver.class)

这里最困难的部分是,您实际上必须编写自定义的ObjectDresolver来解析来自db/其他源的对象。看看我在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。Jackson中的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}]}

此选项很棘手,因为您必须以某种方式删除所有标识信息以进行序列化。一种选择是使用2个对象映射器。1用于序列化,2-nd用于反序列化,并配置某种mixin或JsonView

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

@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;
}

可能更好的方法是以相同的方式为反序列化配置定义JsonIdentityInfo,并删除类上面的所有注释。像这样的

此时,您可能希望只编写自定义序列化器/反序列化器

下面是working(simple Jackson With spring)演示:

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);
    }
}
鲁品
2023-03-14

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

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;
    }
}
 类似资料:
  • 问题内容: @Entity public Product { @Id public int id; 和这个实体: 我希望能够使用JSON发送POST 从客户端 并可以像这样反序列化: 如果它被发送为 我希望它能像现在一样工作 我需要什么样的注释和自定义反序列化器?希望反序列化程序可以对以id为属性的所有可能对象起作用 谢谢! 问题答案: 如果您可以修改实体,则另一种方法是使用工厂方法 甚至像这样的

  • 使用杰克逊( 数据: 数据模型: 我当前的反序列化器如下所示: 注意:我的问题被定义为Scala,但我认为Java的方法足够相似,以至于无关紧要。所以Java的答案是可以接受的。

  • 问题内容: 确定,所以我编辑了问题,因为它不够清楚。 编辑2 :更新了JSON文件。 我在Android应用程序中使用GSON,我需要解析来自服务器的JSON文件,这些文件有点太复杂了。我不想让我的对象结构太沉重,所以我想简化内容: 所以我的对象的结构将不是JSON文件的结构。 例如,如果在JSON中,我有以下内容: 我不想保留我当前的对象结构,即一个对象,其中包含一个和一个“总计”。但是我只想将

  • 问题内容: 我需要反序列化json,它是日期/长值的数组。这是返回的JSON的示例: 使用GSON,我可以将其反序列化为,但希望能够将其转换为类似以下内容的方法: 我似乎找不到一种方法来指示GSON将JSON映射的键/值映射到我的自定义类中的日期/值字段。有没有办法做到这一点,还是地图列表是唯一的路线? 问题答案: 您需要编写一个自定义解串器。您还需要使用可以实际解析的时区格式。无论是也将匹配,这

  • 我有下面的JSON,我正试图使用Jackson API反序列化它 我基本上需要一个附件类,它有一个AttachmentFile对象列表,如下所示: 如何使用自定义反序列化器实现这一点? 谢谢

  • 我使用NewtonSoft.json来反序列化这个json