在Java中将Json的子键的值转换为数组

时间:2018-06-11 01:56:07

标签: java json xml jackson org.json

如果我必须将XML文档信息跟踪到字符串中:

<Collection>
  ...
  <Places><D>USA</D><D>BRAZIL</D><D>COREA</D></Places>
  ...
</Collection>

我希望将其转换为类似于:

的Json
{
  "PLACES": ["USA", "BRAZIL", "COREA"]
}

请注意<D>标记被忽略,我将其中的值作为我想要的值放入我的数组中...如何在java中执行此操作?我正在使用org.json和jackson API执行以下操作:

String xml = FileUtils.readFileToString(new File(file.getAbsolutePath())); 
JSONObject json = org.json.XML.toJSONObject(xml);
ObjectMapper mapper = new ObjectMapper();    
mapper.enable(SerializationFeature.INDENT_OUTPUT)
Object json2 = mapper.readValue(json.toString(), Object.class);
String output = mapper.writeValueAsString(json2);
System.out.println(output);

但它转换信息如下:

{
 "PLACES" : {
    "D" : [ "USA", "BRAZIL", "COREA" ]
  }

所以我希望数组直接在&#34; PLACES&#34;之后,忽略那个&#34; D&#34; ...任何建议?感谢

2 个答案:

答案 0 :(得分:0)

使用XmlMapper将xml转换为POJO。即使您不需要手动读取文件。

POJO(收藏类)

@JacksonXmlRootElement(localName = "Collection")
public class Collection {

    @JsonProperty("PLACES")
    @JacksonXmlProperty(localName = "D")
    @JacksonXmlElementWrapper(localName = "Places")
    List<String> places;

    public List<String> getPlaces() {
        return places;
    }

    public void setPlaces(List<String> places) {
        this.places = places;
    } 
} 

主要方法

public static void main(String[]  args) throws Exception {

    ObjectMapper xmlMapper = new XmlMapper();
    xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);
    Collection c = xmlMapper.readValue(new File("/root/config.txt"), Collection.class);
    System.out.println(xmlMapper.writeValueAsString(c));

    ObjectMapper jsonMapper = new ObjectMapper();
    jsonMapper.enable(SerializationFeature.INDENT_OUTPUT);
    System.out.println(jsonMapper.writeValueAsString(c));
}

<强>输出

<Collection>
  <Places>
    <D>USA</D>
    <D>BRAZIL</D>
    <D>COREA</D>
  </Places>
</Collection>

{
  "PLACES" : [ "USA", "BRAZIL", "COREA" ]
}

Xml库

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.9.5</version>
</dependency>

答案 1 :(得分:0)

SimpleXml和Gson可以做到:

public class Collection {
    public Places Places;
}
public class Places {
    @SerializedName("PLACES")
    public List<String> D;
}

final String data = ...
final SimpleXml simple = new SimpleXml();
final Collection c = simple.fromXml(data, Collection.class);

final Gson gson = new Gson();
System.out.println(gson.toJson(c.Places));

将输出:

{"PLACES":["USA","BRAZIL","COREA"]}

从Maven Central:

<dependency>
    <groupId>com.github.codemonstur</groupId>
    <artifactId>simplexml</artifactId>
    <version>1.4.0</version>
</dependency>

顺便说一句,如果您不喜欢命名,则可以使用SimpleXml批注更改任何内容。我不需要它们,所以我没有使用它们。