我想将xml转换为json。
xml的格式如下 -
<default>
<column>
<title>Title 1</title>
<id>id1</id>
<value>val1</value>
</column>
<column>
<title>Title 2</title>
<id>id2</id>
<value>val2</value>
</column>
<column>
<title>Title 3</title>
<id>id3</id>
<value>val3</value>
</column>
</default>
转换后我期待跟随json -
{
"column": [
{
"title": "Title 1",
"id": "id1",
"value": "val1"
},
{
"title": "Title 2",
"id": "id2",
"value": "val2"
},
{
"title": "Title 3",
"id": "id3",
"value": "val3"
}
]
}
但是当我为此目的使用杰克逊时,它让我跟随json -
{
"column": {
"title": "Title 3",
"id": "id3",
"value": "val3"
}
}
我尝试过使用jackson 1.9和jackson 2.1,但它并没有给我预期的输出。
有人可以告诉我是否可以或我需要更改我的xml格式? 以下是我为实现上述情况而编写的代码 -
try {
XmlMapper xmlMapper = new XmlMapper();
Map entries = xmlMapper.readValue(new File("xmlPath"), Map.class);
ObjectMapper jsonMapper = new ObjectMapper();
String json = jsonMapper.writeValueAsString(entries);
System.out.println(json);
} catch (Exception e) {
e.printStackTrace();
}
由于
答案 0 :(得分:1)
我能够通过使用org.json API将源XML转换为JSONObject然后通过Jackson API转换为JSON来获得此问题的解决方案。
<强>代码强>
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
import org.json.XML;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
...
...
try (InputStream inputStream = new FileInputStream(new File(
"source.xml"))) {
String xml = IOUtils.toString(inputStream);
JSONObject jObject = XML.toJSONObject(xml);
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
Object json = mapper.readValue(jObject.toString(), Object.class);
String output = mapper.writeValueAsString(json);
System.out.println(output);
}
...
...
答案 1 :(得分:0)
在处理群组项目时,我遇到了您所描述的相同问题。我们用来解决这个问题的解决方案是将我们的Maven依赖从Jackson更改为json-lib。我们将此网站用作指南:http://answers.oreilly.com/topic/278-how-to-convert-xml-to-json-in-java/
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<type>jar</type>
<classifier>jdk15</classifier>
<scope>compile</scope>
</dependency>
- $ pli7
答案 2 :(得分:0)
我也使用Jackson 2.5遇到了这个问题。我的解决方案是用我自己的javax.json.JsonObjectBuilder
替换实现,当添加新对象时,行为如下:
public class CustomJsonObjectBuilder implements JsonObjectBuilder {
private final Map<String, JsonValue> jsonFragments;
// other methods omitted for brevity
public JsonObjectBuilder add(String name, JsonValue value) {
if(jsonFragments.containsKey(name)) {
JsonValue oldValue = jsonFragments.get(name);
JsonArrayBuilder newBuilder = new JsonArrayBuilderImpl();
if(oldValue instanceof JsonArray) {
JsonArray theArray = (JsonArray) oldValue;
for (JsonObject oldValues : theArray.getValuesAs(JsonObject.class)) {
newBuilder.add(oldValues);
}
} else {
newBuilder.add(oldValue);
}
newBuilder.add(value);
jsonFragments.put(name, newBuilder.build());
} else {
jsonFragments.put(name, value);
}
return this;
}