gpt4 book ai didi

java - 使用 apache camel 从 xml 转换时,'@' 符号出现在输出 json 中

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:48:37 24 4
gpt4 key购买 nike

我正在尝试使用 apache camel 将 xml 转换为 json,它工作正常。但是输出的每个属性都附加了“@”。

示例:如果 xml 是 AAA,我将在 json 中获取 @name:ajay。

下面是我使用的代码

   XmlJsonDataFormat xmlJsonFormat = new XmlJsonDataFormat();
CamelContext context = new DefaultCamelContext();
try {
xmlJsonFormat.setEncoding("UTF-8");

xmlJsonFormat.setForceTopLevelObject(true);
xmlJsonFormat.setTrimSpaces(true);
xmlJsonFormat.setSkipNamespaces(true);
xmlJsonFormat.setRemoveNamespacePrefixes(true);

context.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
String ch = "" ;
from("file:src/main/resources/input").marshal(xmlJsonFormat).to("file:src/main/resources/output/");

System.out.println(ch);
}
});

context.start();

Thread.sleep(10000);
} finally {
context.stop();
}

最佳答案

作为替代库,您可以使用 JSON.org:

<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>${json.version}</version>
</dependency>

然后像这样实现一个Processor:

public void configure() throws Exception {
from("direct:input")
.convertBodyTo(String.class)
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
final String xmlBody = exchange.getIn().getBody(String.class);
final String jsonBody = XML.toJSONObject(xmlBody).toString();
exchange.getIn().setBody(jsonBody);
}
})
.log("************* My body in json format is ${body} *********")
.to("mock:output");
}

JUnit 测试:

@Test
public void test() throws InterruptedException, CamelExecutionException, IOException {
getMockEndpoint("mock:output").expectedBodyReceived().body().contains("{\"books\"");
getMockEndpoint("mock:output").expectedMessageCount(1);


template.sendBody("direct:input",
IOUtils.toString(this.getClass().getResourceAsStream("/xml/books.xml"),
Charset.defaultCharset()));

getMockEndpoint("mock:output").assertIsSatisfied();
}

鉴于此输入:

<books>
<book>
<title>The Fellowship of the Ring</title>
<author>J.R.R Tolkien</author>
<year>1954</year>
</book>
<book>
<title>The Two Towers</title>
<author>J.R.R Tolkien</author>
<year>1955</year>
</book>
<book>
<title>The Return of the King</title>
<author>J.R.R Tolkien</author>
<year>1956</year>
</book>
</books>

我们有这样的输出:

{
"books":{
"book":[
{
"year":1954,
"author":"J.R.R Tolkien",
"title":"The Fellowship of the Ring"
},
{
"year":1955,
"author":"J.R.R Tolkien",
"title":"The Two Towers"
},
{
"year":1956,
"author":"J.R.R Tolkien",
"title":"The Return of the King"
}
]
}
}

关于java - 使用 apache camel 从 xml 转换时,'@' 符号出现在输出 json 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47546023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com