Spring @RestController 自定义 JSON 反序列化程序

2022-09-03 01:20:08

我想对某些类(此处的角色)使用自定义JSON反序列化程序,但我无法使其正常工作。自定义反序列化程序只是不被调用。

我使用Spring Boot 1.2。

反序列化程序:

public class ModelDeserializer extends JsonDeserializer<Role> {

    @Override
    public Role deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        return null; // this is what should be called but it isn't
    }
}

控制器:

@RestController
public class RoleController {

    @RequestMapping(value = "/role", method = RequestMethod.POST)
    public Object createRole(Role role) {
        // ... this is called
    }
}
  1. @JsonDeserialize在角色上

    @JsonDeserialize(using = ModelDeserializer.class)
    public class Role extends Model {
    
    }
    
  2. Jackson2ObjectMapperBuilderJava Config 中的 bean

    @Bean
    public Jackson2ObjectMapperBuilder jacksonBuilder() {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.deserializerByType(Role.class, new ModelDeserializer());
        return builder;
    }
    

我做错了什么?

编辑它可能是由于它与...@RestController@Controller


答案 1

首先,您无需重写即可添加自定义反序列化程序。当您无法添加批注时,应使用此方法。应使用或覆盖 。Jackson2ObjectMapperBuilder@JsonDeserialize@JsonDeserializeJackson2ObjectMapperBuilder

遗漏的是注释:@RequestBody

@RestController
public class JacksonCustomDesRestEndpoint {

    @RequestMapping(value = "/role", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Object createRole(@RequestBody Role role) {
        return role;
    }
}

@JsonDeserialize(using = RoleDeserializer.class)
public class Role {
    // ......
}

public class RoleDeserializer extends JsonDeserializer<Role> {
    @Override
    public Role deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        // .................
        return something;
    }
}

答案 2

还有另一个非常有趣的解决方案,当您想在调用默认反序列化程序之前修改JSON正文时,它非常有用。让我们想象一下,你需要使用一些额外的豆子(使用机制)@Autowire

让我们想象一下情况,您有以下控制器:

@RequestMapping(value = "/order/product", method = POST)
public <T extends OrderProductInterface> RestGenericResponse orderProduct(@RequestBody @Valid T data) {
    orderService.orderProduct(data);
    return generateResponse();
}

在哪里:OrderProductInterface

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonSerialize(include = NON_EMPTY)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, visible = true, property = "providerType")
@JsonSubTypes({
              @JsonSubTypes.Type(value = OrderProductForARequestData.class, name = "A")
          })
public interface OrderProductInterface{}

上面的代码将根据具体实现提供基于归档和验证的动态反序列化。为了更好地掌握,请考虑可以是这样的:providerTypeOrderProductForARequestData

public class OrderProductForARequestData implements OrderProductInterface {

    @NotBlank(message = "is mandatory field.")
    @Getter @Setter
    private String providerId;

    @NotBlank(message = "is mandatory field.")
    @Getter @Setter
    private String providerType;

    @NotBlank(message = "is mandatory field.")
    @Getter @Setter
    private String productToOrder;

}

现在让我们想象一下,我们希望在执行默认反序列化之前以某种方式初始化(丰富输入)。因此,根据 中的规则,对象将正确反序列化。为此,您可以通过以下方式修改类:providerTypeOrderProductInterface@Configuration

//here can be any annotation which will enable MVC/Boot 
@Configuration
public class YourConfiguration{

    @Autowired
    private ObjectMapper mapper;

    @Autowired
    private ProviderService providerService;

    @Override
    public void setup() {
        super.setup();
        SimpleModule module = new SimpleModule();
        module.setDeserializerModifier(new BeanDeserializerModifier() {
            @Override
            public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) {

                if (beanDesc.getBeanClass() == OrderProductInterface.class) {
                    return new OrderProductInterfaceDeserializer(providerService, beanDesc);
                }
                return deserializer;
            }
        });

        mapper.registerModule(module);
    }

    public static class OrderProductInterfaceDeserializer extends AbstractDeserializer {

            private static final long serialVersionUID = 7923585097068641765L;

            private final ProviderService providerService;

            OrderProductInterfaceDeserializer(roviderService providerService, BeanDescription beanDescription) {
                super(beanDescription);
                this.providerService = providerService;
            }

            @Override
            public Object deserializeWithType(JsonParser p, DeserializationContext context, TypeDeserializer typeDeserializer) throws IOException {
                ObjectCodec oc = p.getCodec();
                JsonNode node = oc.readTree(p);

                //Let's image that we have some identifier for provider type and we want to detect it
                JsonNode tmp = node.get("providerId");
                Assert.notNull(tmp, "'providerId' is mandatory field");
                String providerId = tmp.textValue();
                Assert.hasText(providerId, "'providerId' can't be empty");

                // Modify node
                ((ObjectNode) node).put("providerType",providerService.getProvider(providerId));

                JsonFactory jsonFactory = new JsonFactory();
                JsonParser newParser = jsonFactory.createParser(node.toString());
                newParser.nextToken();

                return super.deserializeWithType(newParser, context, typeDeserializer);

           }

      }
}