欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Mule ESB 学习笔记(12)JSON转换器的使用

程序员文章站 2022-07-12 19:00:56
...

           在许多情况下,可能需要把类转换为json,或者将json转换为xml,xlst等各种格式.这里简单讲解json和xml,xlst等之间的转换过程.

<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns="http://www.mulesoft.org/schema/mule/core"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:json="http://www.mulesoft.org/schema/mule/json"
      xmlns:mxml="http://www.mulesoft.org/schema/mule/xml"
      xmlns:spring="http://www.springframework.org/schema/beans"
      xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
       http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
       http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd
       http://www.mulesoft.org/schema/mule/xml http://www.mulesoft.org/schema/mule/xml/current/mule-xml.xsd">

    <json:is-json-filter name="jsonFilter" validateParsing="true"/>

    <json:mapper name="myMapper">
        <json:mixin mixinClass="com.easyway.esb.mule.json.transformers.FruitCollectionMixin"
                        targetClass="com.easyway.esb.mule.json.transformers.FruitCollection"/>
        <json:mixin mixinClass="com.easyway.esb.mule.json.transformers.AppleMixin"
                        targetClass="com.easyway.esb.mule.json.model.Apple"/>
    </json:mapper>

    <json:json-to-object-transformer name="jsonToFruitCollection" returnClass="com.easyway.esb.mule.json.transformers.FruitCollection"
                                     mapper-ref="myMapper">
        <!-- test augmenting the mixin map with local mixins -->
        <json:deserialization-mixin
                mixinClass="com.easyway.esb.mule.json.transformers.OrangeMixin"
                targetClass="com.easyway.esb.mule.json.model.Orange"/>
    </json:json-to-object-transformer>

    <json:object-to-json-transformer name="fruitCollectionToJson"
                                     sourceClass="com.easyway.esb.mule.json.transformers.FruitCollection">
        <json:serialization-mixin
                mixinClass="com.easyway.esb.mule.json.transformers.FruitCollectionMixin"
                targetClass="com.easyway.esb.mule.json.transformers.FruitCollection"/>
        <json:serialization-mixin
                mixinClass="com.easyway.esb.mule.json.transformers.AppleMixin"
                targetClass="com.easyway.esb.mule.json.model.Apple"/>
        <json:serialization-mixin
                mixinClass="com.easyway.esb.mule.json.transformers.OrangeMixin"
                targetClass="com.easyway.esb.mule.json.model.Orange"/>
    </json:object-to-json-transformer>

    <json:json-to-xml-transformer name="jToX"/>

    <json:xml-to-json-transformer name="xToJ"/>

    <json:json-xslt-transformer name="jToJ">
        <mxml:xslt-text>
            <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
                <xsl:template match="@*|node()">
                    <xsl:copy>
                        <xsl:apply-templates select="@*|node()"/>
                    </xsl:copy>
                </xsl:template>
            </xsl:stylesheet>
        </mxml:xslt-text>
    </json:json-xslt-transformer>

    <json:json-schema-validation-filter name="jvf" schemaLocations="customer.xsd"/>

</mule>

 

 

测试代码:

  XmlToJson transformer = new XmlToJson();
        String jsonResponse = (String) transformer.transform(XML);
        System.out.println("jsonResponse ="+jsonResponse);
        
        StringReader reader = new StringReader(XML);

        transformer = new XmlToJson();
        jsonResponse = (String) transformer.transform(reader);
        System.out.println("jsonResponse ="+jsonResponse);
        
        byte[] bytes = XML.getBytes();
        transformer = new XmlToJson();
        jsonResponse = (String) transformer.transform(bytes);
        System.out.println("jsonResponse ="+jsonResponse);
        
        Document document = XMLUtils.toW3cDocument(XML);
        document.setDocumentURI("xxx");
        transformer = new XmlToJson();
        jsonResponse = (String) transformer.transform(document);
        System.out.println("jsonResponse ="+jsonResponse);
        

  

 

mule-jdbc-json-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns="http://www.mulesoft.org/schema/mule/core"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:spring="http://www.springframework.org/schema/beans"
      xmlns:quartz="http://www.mulesoft.org/schema/mule/quartz"
       xmlns:jdbc="http://www.mulesoft.org/schema/mule/jdbc"
        xmlns:http="http://www.mulesoft.org/schema/mule/http"
          xmlns:json="http://www.mulesoft.org/schema/mule/json"
      xmlns:https="http://www.mulesoft.org/schema/mule/https"
      xmlns:test="http://www.mulesoft.org/schema/mule/test"
      xsi:schemaLocation="
       http://www.mulesoft.org/schema/mule/test http://www.mulesoft.org/schema/mule/test/current/mule-test.xsd
       http://www.mulesoft.org/schema/mule/jdbc http://www.mulesoft.org/schema/mule/jdbc/current/mule-jdbc.xsd
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
       http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
       http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd       
       http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
       http://www.mulesoft.org/schema/mule/https http://www.mulesoft.org/schema/mule/https/current/mule-https.xsd       
       http://www.mulesoft.org/schema/mule/quartz http://www.mulesoft.org/schema/mule/quartz/current/mule-quartz.xsd">

     <jdbc:mysql-data-source name="MySQL_Data_Source1" url="jdbc:mysql://localhost:3306/dbtest2" user="root" password="root" transactionIsolation="UNSPECIFIED" />
   
    <jdbc:connector name="Database" dataSource-ref="MySQL_Data_Source1" validateConnections="true" queryTimeout="-1" pollingFrequency="0" />
   
    <flow name="httpPostTestFlow1" > 
        <http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="8081" path="httpPost" ></http:inbound-endpoint>
        <json:json-to-object-transformer  returnClass="java.util.Map"></json:json-to-object-transformer>
        <jdbc:outbound-endpoint exchange-pattern="one-way" queryTimeout="-1"  queryKey="INSERT_TOKEN" connector-ref="Database">
            <jdbc:query key="INSERT_TOKEN" value="insert into user(FirstName) values(#[message.payload.name]);"/>
        </jdbc:outbound-endpoint>   
    </flow>
</mule>

 

服务端代码:
public class JSONJdbcServerMain
{

  public static void main(String[] args) {
      try {
          String configFile = "mule-jdbc-json-config.xml";
          String[] configFileArr = new String[] {configFile };
          MuleContextFactory muleContextFactory = new DefaultMuleContextFactory();
          MuleContext muleContext = muleContextFactory
                  .createMuleContext(new SpringXmlConfigurationBuilder(configFileArr));
          muleContext.start();
      } catch (Exception e) {
          e.printStackTrace();
      }
  
   }
}
 
客户端代码:

                        原来 Java 项目中用的 JSON 组件库主要是 Gson 和 json-lib,Gson 算是很错的库,json-lib 略显寒碜。好啦,最近 Play 2.x 中弃用了 Gson 而采纳了 Jackson,所以现在就来打探一下 Jackson,踩个点吧。

Jackson 号称非常高的性能,听说比另两位兄弟 Gson 和 json-lib 高出一大截,我没有亲测,可是有心人做了,看这个链接 两款JSON类库Jackson与JSON-lib的性能对比(新增第三款测试) 中的数据。2010 年 8 月份的测试结果,不知现在随着版本的变更是否仍然保持着这种悬殊。

 

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;

/**
 * <p>功能描述,该部分必须以中文句号结尾。<p>
 *
 * 创建日期 2013-8-22<br>
 * @author  $Author$<br>
 * @version $Revision$ $Date$
 * @since   3.0.0
 */
public class MuleJSONJdbcClientMain {
    public static void main(String[] args) {
        // 构造HttpClient的实例
        HttpClient httpClient = new HttpClient();
        // 创建GET方法的实例
        PostMethod postMethod = new PostMethod("http://localhost:8081/httpPost");
        // 使用系统提供的默认的恢复策略
        postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        try {
            // 执行getMethod
            
            //将对象转换JSON
            ObjectMapper mapper = new ObjectMapper();
            mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
            mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
            Map<String,String> paramMap=new HashMap<String,String>();
            paramMap.put("id", "345");
            paramMap.put("name", "xiaobai");
            String jsonx = mapper.writeValueAsString(paramMap);
            
            //将json转换为对象
            Map<?, ?> map = mapper.readValue(jsonx, Map.class);
            System.out.println("map=" + map.toString());
            
            //设置JSON数据信息
            postMethod.setRequestEntity(new StringRequestEntity(jsonx));
            
            //发送http请求
            int statusCode = httpClient.executeMethod(postMethod);
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method failed: " + postMethod.getStatusLine());
            }
            // 读取内容
            byte[] inputStream = postMethod.getResponseBody();
            // 处理内容
            System.out.println("responseBody=" + new String(inputStream, "UTF-8"));
        } catch (HttpException e) {
            // 发生致命的异常,可能是协议不对或者返回的内容有问题
            System.out.println("Please check your provided http address!");
            e.printStackTrace();
        } catch (IOException e) {
            // 发生网络异常
            e.printStackTrace();
        } finally {
            // 释放连接
            postMethod.releaseConnection();
        }
    }
}