English 中文(简体)
WSO2 ESSB 无法将完整的 JSON 数据转换为 XML
原标题:WSO2 ESB Unable to convert complete JSON data to XML

I am constructing a POC. And I created a pass through proxy service for Google Plus. Without using any proxy service I get this is my output :

 {
   "kind":"plus#person",
   "etag":""ExituU7aUpmkkfyD52VulzptThw/4J1clegrhxYC2fsJOu2XWCs1Ewg"",
   "id":"117488614303967062311",
   "displayName":"Abhi NeoN",
   "name":{
      "familyName":"NeoN",
      "givenName":"Abhi"
   },
   "tagline":"hey guys ! ssup!! check out ma recnt videos... uploaded",
   "gender":"male",
   "aboutMe":"u003cbu003ehie, abhishek - ma full name u003c/bu003eu003cdivu003eu003cbu003em a DANCER ,u003c/bu003eu003c/divu003eu003cdivu003eu003cbu003ei luv ma dancing .u003c/bu003eu003c/divu003eu003cdivu003eu003cbu003ei care ma dancing ,u003c/bu003eu003c/divu003eu003cdivu003eu003cbu003ei jus hv a gr8 thng in me dats ma dancing.u003c/bu003eu003c/divu003e",
   "relationshipStatus":"single",
   "url":"https://plus.google.com/117488614303967062311",
   "image":{
      "url":"https://lh6.googleusercontent.com/-tF-ip0tUxD4/AAAAAAAAAAI/AAAAAAAAAAA/WKI3USUh_DA/photo.jpg?sz=50"
   },
   "urls":[
      {
         "value":"https://plus.google.com/117488614303967062311",
         "type":"profile"
      },
      {
         "value":"https://www.googleapis.com/plus/v1/people/117488614303967062311",
         "type":"json"
      }
   ],
   "organizations":[
      {
         "name":"our lady of nazareth high school",
         "title":"science",
         "type":"school"
      },
      {
         "name":"",
         "title":"BLUEBYTES",
         "type":"work"
      }
   ]
}

但当我试图做同样的事情 使用简单的通过服务 我只能得到:

{
   "kind":"plus#person"
}

I read on the wso2esb site that they had a bug and the explanation given to resolve the bug was that json data received was not in the proper format. But now how do I resolve the problem. I mean is their any way I can manipulate the json data before the esb converts it into json data.

最佳回答

我们在最近发布的ESB(4.5.0版)中解决了这一问题。 默认情况下,它涉及JSONMessage Formatter/JSONBuilder, 它可以用多个密钥处理JSON的有效载荷。

我们还提出了处理涉及不同类型 JSON & lt;- & gt; XML (或 JSON & lt;- & gt; JSON) 转换的电文流的另一种解决办法。 JSONStreamBuilder JSONSONStreamFormatter 可用于与脚本调解员执行这种情景。 请查看ESB 4. 5. 0 中的样本 # 441 。

运行样本#441;

  • Add JSONStreamBuilder and JSONStreamFormatter as the builder and formatter for JSON in repository/conf/axis2/axis2.xml file
  • Deploy SimpleStockQuoteService
  • Start the sample axis2server
  • Run the JSON client with ant newjsonclient
问题回答

这是当前轴2 JSON 建设器/ 事项的局限性之一。 我们目前正在为 JSON 开发一个新的建筑/ 事项配对, 不转换 JSON & lt; & gt; XML 。 相反, 它( 创建者) 将 JSON 信息作为流存储, 并且可以使用脚本调解人从流中构建 JSON 对象 。 例如, 如果我们发送 {"a" : "x" 、 "b" : "y" 作为请求, 在 ESB 中, 我们可以将请求作为 JSON 对象, 使用 Javascript 。

var a = mc.getJSON().a.toString();
var b = mc.getJSON().b.toString();
mc.setPayloadXML(
    <m:A xmlns:m="http://example.json">
        <m:a>{a}</m:a>
        <m:b>{b}</m:b>
    </m:A>);

同样, mc.setJSON () 方法可用于设置任意的 JSON 对象。

The only way to reliably convert json to xml and back again is via the use of type hints in the xml. the default converter does not do this. it 1. drops everything after the first property 2. confuses single element lists with properties when going from xml to json

i 已使用json- util 库重新实施转基因分类, 该库将 json 转换为 xml, 内含作为元素属性的类型提示, 以确保没有模糊性 。

这样我们就可以通过WSO2, 智能地代理所有json提供的无问题休息服务(即内容路线和运输和有效载荷的中转)

这解决了问题(我认为骆驼是默认情况下这样做的)。

以下是波姆文件及代码:

<强 > 将罐装罐装成/存储/组件/ lib < / 强 >

您必须更新轴 2. xml 中内容类型“ 应用程序/ json” 的信息格式和信息创建器映射图


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <name>wso2 json/xml converter</name>
    <groupId>x.y.z</groupId>
    <artifactId>wso2converter</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <jdk.version>1.6</jdk.version>
    </properties>

    <build>
        <finalName>wso2converter</finalName>
        <resources>
            <resource>
                <filtering>false</filtering>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-enforcer-plugin</artifactId>
                <version>1.0.1</version>
                <executions>
                    <execution>
                        <id>enforce-jdk</id>
                        <phase>validate</phase>
                        <goals>
                            <goal>display-info</goal>
                            <goal>enforce</goal>
                        </goals>
                        <configuration>
                            <rules>
                                <requireJavaVersion>
                                    <version>[${jdk.version},)</version>
                                </requireJavaVersion>
                            </rules>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.3</version>
            <classifier>jdk15</classifier>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.ws.commons.axiom</groupId>
            <artifactId>axiom-api</artifactId>
            <version>1.2.13</version>
        </dependency>

        <dependency>
            <groupId>org.apache.axis2</groupId>
            <artifactId>axis2-kernel</artifactId>
            <version>1.6.2</version>
        </dependency>

        <dependency>
            <groupId>xom</groupId>
            <artifactId>xom</artifactId>
            <version>1.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.synapse</groupId>
            <artifactId>synapse-core</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>1.1.5</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.13</version>
            <!--scope>provided</scope-->
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>

package a.b.wso2;

import java.io.InputStream;
import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.xml.XMLSerializer;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.util.AXIOMUtil;
import org.apache.axis2.AxisFault;
import org.apache.axis2.builder.Builder;
import org.apache.axis2.context.MessageContext;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;


public class WsoJtoX implements Builder {

    Logger logger = Logger.getLogger("a.b.wso2converter");

    @Override
    public OMElement processDocument(InputStream is, String contentType,
            MessageContext messageContext) throws AxisFault {
        String jsonData = "";
        try {

            jsonData = IOUtils.toString(is,"UTF-8");


            String output = process(jsonData);

            OMElement e = AXIOMUtil.stringToOM(output);
            return e;


        } catch (Exception e) {
            logger.error("error converting json string " + jsonData, e);
            if (e instanceof AxisFault) {
                throw (AxisFault) e;
            }
            throw new AxisFault("(B"+counter+") error converting json to xml", e);
        }

    }

    static int counter=0;

    public String process(String jsonData) throws AxisFault {

        try {
            String tran = "__ns__";

            jsonData=jsonData.replace("
", "").trim();
            //jsonData=jsonData.replace("
", "");

            String decoded = (jsonData.replaceAll(""([a-zA-Z0-9_]*)\:([a-zA-Z0-9]*)"(\s*)(:)", ""$1" + tran + "$2"$3:"));

            counter++;

            if (logger.isDebugEnabled()) {
                logger.debug("
>>>>> (B"+counter+") converting json
 " + jsonData + "
====");
            }

            XMLSerializer serializer = new XMLSerializer();
            JSON json = JSONSerializer.toJSON(decoded);

            String xml = serializer.write(json);

            //add in the soap stuff
            StringBuilder sb = new StringBuilder();
            sb.append("<soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <soap:Body>");
            sb.append(xml.replace("<?xml version="1.0" encoding="UTF-8"?>", ""));
            sb.append("</soap:Body></soap:Envelope>");

            if (logger.isDebugEnabled()) {
                logger.debug("
==== (B"+counter+") to xml
" + sb.toString()+"
<<<<<");
            }

            return sb.toString();


        } catch (Exception e) {
            throw new AxisFault("(B"+counter+") error transforming json to xml", e);
        }

    }

}

package a.b.wso2;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import net.sf.json.JSON;

import net.sf.json.xml.XMLSerializer;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMOutputFormat;
import org.apache.axiom.om.util.AXIOMUtil;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.transport.MessageFormatter;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

public class WsoXtoJ implements MessageFormatter {

    Logger logger = Logger.getLogger("a.b.wso2converter");

    private static int counter=0;

    public String convert(String xData) {

        counter++;

            if (logger.isDebugEnabled()) {
                logger.debug("
]]]]] (A"+counter+") converting xml
 " + xData + "
-----");
            }


        try {
            String tran = "__ns__";
            XMLSerializer serializer = new XMLSerializer();
            OMElement e = AXIOMUtil.stringToOM(xData);
            OMElement b = (OMElement) e.getChildrenWithLocalName("Body").next();
            b = (OMElement) b.getChildElements().next();
            String xfrag = b.toStringWithConsume();
            String str = "";
            JSON j = serializer.read(xfrag);
            str = j.toString();
            String nstr = str.replaceAll(""([a-zA-Z0-9_]+)" + tran + "([a-zA-Z0-9]+)"(\s*)(:)", ""$1:$2"$3:");  //", ""$1:$2"");

            if (logger.isDebugEnabled()) {
                logger.debug("
----- (A"+counter+") to json
" + nstr+"
[[[[[");
            }

            return nstr;

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public String formatSOAPAction(MessageContext msgCtxt, OMOutputFormat format,
            String soapActionString) {
        return null;
    }

    @Override
    public byte[] getBytes(MessageContext ctx, OMOutputFormat format)
            throws AxisFault {
        String env="";
        try {
            OMElement element = ctx.getEnvelope().getBody().getFirstElement();
            String payload = this.convert(element.toString());
            return payload.getBytes(format.getCharSetEncoding());
        } catch (UnsupportedEncodingException e) {
            logger.error("(A"+counter+") error converting xml to json "+ctx.getEnvelope().toString());
            throw AxisFault.makeFault(e);
        }
    }

    @Override
    public String getContentType(MessageContext msgCtxt, OMOutputFormat format,
            String soapActionString) {
        String contentType = (String) msgCtxt.getProperty(Constants.Configuration.CONTENT_TYPE);
        String encoding = format.getCharSetEncoding();
        if (contentType == null) {
            contentType = (String) msgCtxt.getProperty(Constants.Configuration.MESSAGE_TYPE);
        }
        if (encoding != null) {
            contentType += "; charset=" + encoding;
        }
        return contentType;
    }

    @Override
    public URL getTargetAddress(MessageContext msgCtxt, OMOutputFormat format,
            URL targetURL) throws AxisFault {
        return targetURL;
    }

    @Override
    public void writeTo(MessageContext msgCtxt, OMOutputFormat format,
            OutputStream out, boolean preserve) throws AxisFault {
        try {
            out.write(this.getBytes(msgCtxt, format));
            out.flush();
        } catch (IOException e) {
            throw AxisFault.makeFault(e);
        }
    }

}

我也有同样的问题

依据我的经验,WSO2 ESB(基于Axis2-json)的JSON教授只支持JSON的一个子集:

  1. JSON必须从"{"开始,也就是说,根部不能有JSONArray。

  2. 只考虑第一个关键值对。 这是因为 JSON 被映射到类似 XML 的数据结构中, XML 必须有一个根, 所以第一个关键值对被视为 root 。

  3. 第一个键值对的值不能是一个数组。 因为转换器必须知道每个值应该使用哪个 XML 标记 :

    例如 :... {“ 关键 ” : [“ val1 ”, “ val2 ”,...} - & gt; & lt; key> val1 & lt; / key> & lt; key> ; val2 & lt; / key & gt;...

我在这里也有同样的问题, 想要找到一个解决办法。 我的想法是创建一个新的 JSONBuilder( 建立内部 SOAP 信件构造的解析器) 和 JSONFormatter( 序列器) 来使用虚拟根( 例如 { " 坚固 > 根 < / 坚固 > :...} 来伪造解析器 。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签