首页 > 解决方案 > json 到对象转换期间的异常:无法解析 'javaTypes' 中的 'json__TypeId__'

问题描述

我正在读取带有 json 消息的队列,并且在侦听器中我试图将消息作为来自该 json 的对象访问。这是使用的转换器:

@Bean // Serialize message content to json using TextMessage
public MessageConverter jacksonJmsMessageConverter() {
    MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
    converter.setTargetType(MessageType.TEXT);
    converter.setTypeIdPropertyName("BrokerTrade.class");
    return converter;
}

我面临以下异常。

org.springframework.integration.transformer.MessageTransformationException: failed to transform message; nested exception is java.lang.IllegalArgumentException: Could not resolve 'json__TypeId__' in 'javaTypes'.

以下是示例 json,我使用 jmsTemplate 将其添加到队列中。

{ “id”:1,“tradeSourceId”:“mytradeSourceId”,“messageOriginCode”:“CXE”,“sequenceNumber”:“1”,“messageType”:“TRANSFER”,“movementCode”:“1”,“transferType” :“正常”,“updateType”:“无更新”}

请帮忙。

标签: jsonjmsactivemqspring-jms

解决方案


>converter.setTypeIdPropertyName("BrokerTrade.class");

这应该是消息中包含有关要转换为的类型的信息的 String 属性的名称 - 要在类映射中查找以确定类名的值的完全限定类名。

如果消息不包含类型信息,则必须对转换器进行子类化并覆盖getJavaTypeForMessage以返回 Jackson JavaType...

/**
 * Determine a Jackson JavaType for the given JMS Message,
 * typically parsing a type id message property.
 * <p>The default implementation parses the configured type id property name
 * and consults the configured type id mapping. This can be overridden with
 * a different strategy, e.g. doing some heuristics based on message origin.
 * @param message the JMS Message to set the type id on
 * @throws JMSException if thrown by JMS methods
 * @see #setTypeIdOnMessage(Object, javax.jms.Message)
 * @see #setTypeIdPropertyName(String)
 * @see #setTypeIdMappings(java.util.Map)
 */
protected JavaType getJavaTypeForMessage(Message message) throws JMSException {
...
}

您通常可以使用 objectMapper 来做到这一点......

objectMapper.getTypeFactory().constructType(BrokerTrade.class)

推荐阅读