com.fasterxml.jackson.databind.exc.MismatchedInputException:无法从START_OBJECT令牌中反序列化java.lang.String实例

问题描述

我使用Spring Boot和Rappitmq来实现两个不同应用程序之间的异步消息传递。当我仅将字符串作为消息内容交换时,这可以很好地工作。我还促进了波霍舞的交流。由于pojos蜂在不同的程序包中,所以序列化/反序列化过程失败。为了解决这个问题,我使用JacksonConverter使用json。正如我在订阅者服务“ application / json”的消息头中看到的那样,它起作用

要交换的模型(发布和订阅服务中相同):

public class Employee{

private Integer id;
private String firstName;
private String lastName;
private Double salary;

public Employee(@JsonProperty("id") Integer id,@JsonProperty("firstName") String firstName,@JsonProperty("lastName") String lastName,@JsonProperty("salary") Double salary) {
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.salary = salary;
}

public Integer getId() {
    return id;
}

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

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public Double getSalary() {
    return salary;
}

public void setSalary(Double salary) {
    this.salary = salary;
}

@Override
public String toString() {
    return "{" +
            "id=" + id +
            ",firstName='" + firstName + '\'' +
            ",lastName='" + lastName + '\'' +
            ",salary=" + salary +
            '}';
}

Beans在发布者服务中使用Jackson2JsonConverter:

 @SpringBootApplication
public class PublisherApplication {

public static void main(String[] args) {

    SpringApplication.run(PublisherApplication.class,args);

}

@Bean
public Jackson2JsonMessageConverter producerMessageConverter(){
    return new Jackson2JsonMessageConverter();
}

@Bean
public RabbitTemplate rabbitTemplate(final ConnectionFactory connectionFactory){
    RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
    rabbitTemplate.setMessageConverter(producerMessageConverter());
    return rabbitTemplate;
}

}

发送消息:

    @Override
public void sendEmployeeObject(Employee employee) throws JsonProcessingException {
    rabbitTemplate.convertAndSend(RabbitMqConstants.EXCHANGE_NAME,"foo.bar.baz",employee);
}

}

订户配置:

   @Configuration
public class EmployeeMessageSubscriberConfig {

@Bean
@Qualifier("employeeQueue")
Queue queue() {
    return new Queue(RabbitMqConstants.EMPLOYEE_QUEUE,false);
}

@Bean
@Qualifier("employeeExchange")
TopicExchange exchange() {
    return new TopicExchange(RabbitMqConstants.EXCHANGE_NAME);
}

@Bean
@Qualifier("employeeQueueExchangeBinding")
Binding binding(Queue queue,TopicExchange exchange) {
    return BindingBuilder.bind(queue).to(exchange).with("foo.bar.#");
}
@Bean
public Jackson2JsonMessageConverter converter() {
    return new Jackson2JsonMessageConverter();
}

}

侦听器方法:

 @RabbitListener(queues = RabbitMqConstants.EMPLOYEE_QUEUE)
    public void handleMessage(Employee employee) {

        System.out.println("Received <" + employee.toString() + ">");
    }

要测试它,我通过rest api将Employee对象发送到发布者服务。在这里,我只是将其原样传递给Rabbit。订户服务读取消息,然后将其打印到控制台。

问题: 订户服务将打印正确的值:

Received <{id=1,firstName='John',lastName='Doe',salary=1.5}>

但是我也得到了错误跟踪:

    Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.String` out of START_OBJECT token
 at [Source: (String)"{"id":1,"firstName":"John","lastName":"Doe","salary":1.5}"; line: 1,column: 1]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) 

据我所知,订户看到传入的Json是ob类型的Object,但它尝试将其反序列化为String。

问题: 当跟踪显示似乎有错误时,为什么打印出正确的输出? 当我使用RestController时,传入的对象会自动映射到给定的Model。使用Rabbitmq时是否必须以某种方式将其连接起来?

编辑:

这就是我遵循的guide

正如我在订户的标题中看到的那样,有一个字段headers={__TypeId__=com.publisher.model.Employee},所以我已经在两个应用程序中将Employee模型设置为一个具有相同名称的包。还是一样的错误。 (就像我预期的那样,因为与standardMessageConverter相反,包名称未用于序列化)

解决方法

很明显,您不能直接通过Java Bean接收消息。

尝试使用byte[] msgString msg作为handleMessage()方法的参数,并将其手动转换为Employee bean。

如果要使用Java Bean接收消息,则配置会有所帮助。

@Configuration
public class RabbitMQConfig {
    
    @Bean
    public RabbitListenerContainerFactory<?> rabbitListenerContainerFactory(ConnectionFactory connectionFactory){
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(new Jackson2JsonMessageConverter());
        return factory;
    }

}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...