2013-10-11 4 views
1

Это похоже на такую ​​простую вещь, но я не могу найти ее в документации Camel.Как преобразовать карту, возвращенную Camel в JSON?

В связи с моим последним вопросом i.e, Get BeanCreationException when try to add Jackson Library Теперь у меня есть код, который отправляет сообщения ответа JMS-сообщений в формате JSON.

Вот что я в настоящее время получаю, когда я запускаю мой код:

23118 [hello.world.request.timer] INFO hello.world.request - Exchange[Id:e93861e4- a5be-4d63-b658-5939f414e595, ExchangePattern:InOnly, Properties: {CamelToEndpoint=log://hello.world.request?showAll=true, CamelTimerFiredTime=Fri Oct 11  12:03:20 EDT 2013, CamelTimerPeriod=10000, CamelTimerName=hello.world.request.timer},  Headers:{firedTime=Fri Oct 11 12:03:20 EDT 2013}, BodyType:null, Body:null, Out: null] 

Returning Map 
key= fruit1DataType, value= String 
key= fruit1, value= apple 
key= fruit1Calories, value= 95 
key= fruit1ColorDataType, value= String 
key= fruit1CaloriesDataType, value= int 
key= fruit1Color, value= red 
23122 [hello.world.request.timer] INFO hello.world.response - Exchange[Id:e93861e4- a5be-4d63-b658-5939f414e595, ExchangePattern:InOnly, Properties: {CamelToEndpoint=log://hello.world.response?showAll=true, CamelTimerFiredTime=Fri Oct 11  12:03:20 EDT 2013, CamelTimerPeriod=10000, CamelTimerName=hello.world.request.timer},  Headers:{firedTime=Fri Oct 11 12:03:20 EDT 2013}, BodyType:byte[], Body: {"fruit1DataType":"String","fruit1":"apple","fruit1Calories":"95","fruit1ColorDataType":"St ring","fruit1CaloriesDataType":"int","fruit1Color":"red"}, Out: null] 

В идеале я бы хотел, чтобы верблюд конвертировать содержимое карты возвращается в формате JSON и распечатать его на консоль, как это:

{"fruit1DataType":"String","fruit1":"apple","fruit1Calories":"95","fruit1ColorDataType":"String","fruit1CaloriesDataType":"int","fruit1Color":"red"}, Out: null] 

Как изменить свой applicationContext.xml, чтобы Camel это сделал?

Вот мой текущий applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?> 

<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:camel="http://camel.apache.org/schema/spring" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:util="http://www.springframework.org/schema/util" 
    xsi:schemaLocation=" 
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
     http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd 
     http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> 

    <bean 
     class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" /> 
    <context:component-scan base-package="sample" /> 
    <context:annotation-config /> 

    <camel:camelContext id="HelloWorldContext"> 

     <!-- Add Jackson library to render Java Map into JSON --> 
     <camel:dataFormats> 
      <camel:json id="jack" library="Jackson"/> 
     </camel:dataFormats> 

     <camel:route> 
      <!-- sends a request to the hello world JMS queue every 10 seconds --> 
      <camel:from 
       uri="timer://hello.world.request.timer?fixedRate=true&amp;period=10000" /> 
      <camel:to uri="log:hello.world.request?level=INFO?showAll=true" /> 
      <camel:bean ref="helloWorld" /> 

      <!-- now print out the map in JSON format --> 
      <camel:marshal ref ="jack"/> 
      <camel:to uri="log:hello.world.response?level=INFO?showAll=true" /> 
     </camel:route> 

    </camel:camelContext> 

    <bean id="jms" class="org.apache.activemq.camel.component.ActiveMQComponent"> 
     <property name="configuration" ref="jmsConfig" /> 
    </bean> 

    <bean id="jmsConfig" class="org.apache.camel.component.jms.JmsConfiguration"> 
     <property name="connectionFactory" ref="jmsConnectionFactory" /> 
     <property name="transacted" value="false" /> 
     <property name="concurrentConsumers" value="1" /> 
    </bean> 

    <bean id="jmsConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory"> 
     <property name="brokerURL" value="vm://localhost" /> 
     <property name="redeliveryPolicy" ref="redeliveryPolicy" /> 
     <property name="prefetchPolicy" ref="prefetchPolicy" /> 
    </bean> 

    <bean id="prefetchPolicy" class="org.apache.activemq.ActiveMQPrefetchPolicy"> 
     <property name="queuePrefetch" value="5" /> 
    </bean> 

    <bean id="redeliveryPolicy" class="org.apache.activemq.RedeliveryPolicy"> 
     <property name="maximumRedeliveries" value="1" /> 
     <property name="backOffMultiplier" value="2" /> 
     <property name="initialRedeliveryDelay" value="2000" /> 
    </bean> 

</beans> 

ответ

0

Вам нужен верблюд JSON endpoint в вашем пути к сериализации Map в формате JSON. Ссылка также показывает, как вы можете выбрать, какой сериализатор (Джексон - лучший выбор, на мой взгляд) для использования в вашей конечной точке.

Что-то вроде этого (не точно)

<camelContext> 
     <dataFormats> 
      <json id="serializer" library="Jackson"/> 
     </dataFormats> 
     <route> 
      <from uri="servlet:///test-camel"/> 
      <to uri="bean:someSpringBean"/> 
      <to uri="bean:anotherSpringBean"/> 
      <marshal ref="serializer"/> 
     </route>    
</camelContext> 

Обратите внимание, что json элемент также имеет атрибут называется unmarshalTypeName для типа сериализации из/десериализации в. Однако это значение по умолчанию равно Map, как описано в ссылке, упомянутой выше. Поскольку у вас есть Map, вам не нужно указывать.

+0

Я предполагаю, что вы ссылаетесь этот пример: <от URI = "прямой: назад "/> Я пробовал играть с этим, но не получил его на работу. Думаю, я еще не понимаю синтаксиса. Не могли бы вы привести пример, связанный с моим applicationContext.xml? – erj2code

+0

Я нашел эту страницу по теме Camel: http://camel.apache.org/how-do-i-configure-endpoints.html. Раздел под заголовком «Использование Spring XML» был бы наиболее связан с тем, что я хочу, но как мне использовать, чтобы сериализовать мою карту в JSON? – erj2code

+0

Vidya, не могли бы вы представить мне простой пример конечной точки Camel JSON? – erj2code

0

Вы можете сделать это простым способом:

<route> 
    <from id="from1" uri="anyway" /> 
    <marshal id="_marshal1"> 
     <json library="Jackson"/> 
    </marshal> 
    <log id="_log1" message="${body}"/> 
    <to id="_to1" uri="mock:foo"/> 
</route> 

И импортировать зависимость в .pom

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core --> 
<dependency> 
    <groupId>org.apache.camel</groupId> 
    <artifactId>camel-jackson</artifactId> 
    <version>2.9.2</version> 
</dependency> 
Смежные вопросы