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

阅读更多

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




    

    
        
        
    

    
        
        
    

    
        
        
        
    

    

    

    
        
            
                
                    
                        
                    
                
            
        
    

    


 

 

测试代码:

  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:




     
   
    
   
     
        
        
        
            
           
    

 

服务端代码:
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;

/**
 * 

功能描述,该部分必须以中文句号结尾。

* * 创建日期 2013-8-22
* @author $Author$
* @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 paramMap=new HashMap(); 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(); } } }

  

你可能感兴趣的:(mule,ESB,SOA,JSON,Transformer,Jackson)