将Json转换为Xml的最简单方法

时间:2011-07-19 05:37:51

标签: java android xml json

我在.net中有网络服务。当我从数据库中检索数据时,它返回Android Mobile中的JSON文件。如何将JSON文件转换为XML或文本。

5 个答案:

答案 0 :(得分:9)

对于一个简单的解决方案,我推荐Jackson,因为它可以通过几行简单的代码将任意复杂的JSON转换为XML。

import org.codehaus.jackson.map.ObjectMapper;

import com.fasterxml.jackson.xml.XmlMapper;

public class Foo
{
  public String name;
  public Bar bar;

  public static void main(String[] args) throws Exception
  {
    // JSON input: {"name":"FOO","bar":{"id":42}}
    String jsonInput = "{\"name\":\"FOO\",\"bar\":{\"id\":42}}";

    ObjectMapper jsonMapper = new ObjectMapper();
    Foo foo = jsonMapper.readValue(jsonInput, Foo.class);

    XmlMapper xmlMapper = new XmlMapper();
    System.out.println(xmlMapper.writeValueAsString(foo));
    // <Foo xmlns=""><name>FOO</name><bar><id>42</id></bar></Foo>
  }
}

class Bar
{
  public int id;
}

此演示使用Jackson 1.7.7(较新的1.7.8也可以使用),Jackson XML Databind 0.5.3(尚未与Jackson 1.8兼容)和Stax2 3.1.1

答案 1 :(得分:4)

以下是如何执行此操作,生成有效XML的示例。我还在Maven项目中使用Jackson库。

Maven设置:

<!-- https://mvnrepository.com/artifact/com.fasterxml/jackson-xml-databind -->
    <dependency>
        <groupId>com.fasterxml</groupId>
        <artifactId>jackson-xml-databind</artifactId>
        <version>0.6.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.6</version>
    </dependency>

这是一些Java代码,它首先将JSON字符串转换为对象,然后使用XMLMapper将对象转换为XML,并删除任何错误的元素名称。替换XML元素名称中的错误字符的原因是您可以在$ oid等JSON元素名称中使用XML中不允许的字符。杰克逊图书馆没有考虑到这一点,所以我最后添加了一些代码,从元素名称和名称空间声明中删除非法字符。

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.xml.XmlMapper;

import java.io.IOException;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Converts JSON to XML and makes sure the resulting XML 
 * does not have invalid element names.
 */
public class JsonToXMLConverter {

    private static final Pattern XML_TAG =
            Pattern.compile("(?m)(?s)(?i)(?<first><(/)?)(?<nonXml>.+?)(?<last>(/)?>)");

    private static final Pattern REMOVE_ILLEGAL_CHARS = 
            Pattern.compile("(i?)([^\\s=\"'a-zA-Z0-9._-])|(xmlns=\"[^\"]*\")");

    private ObjectMapper mapper = new ObjectMapper();

    private XmlMapper xmlMapper = new XmlMapper();

    String convertToXml(Object obj) throws IOException {
        final String s = xmlMapper.writeValueAsString(obj);
        return removeIllegalXmlChars(s);
    }

    private String removeIllegalXmlChars(String s) {
        final Matcher matcher = XML_TAG.matcher(s);
        StringBuffer sb = new StringBuffer();
        while(matcher.find()) {
            String elementName = REMOVE_ILLEGAL_CHARS.matcher(matcher.group("nonXml"))
                    .replaceAll("").trim();
            matcher.appendReplacement(sb, "${first}" + elementName + "${last}");
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    Map<String, Object> convertJson(String json) throws IOException {
        return mapper.readValue(json, new TypeReference<Map<String, Object>>(){});
    }

    public String convertJsonToXml(String json) throws IOException {
        return convertToXml(convertJson(json));
    }
}

以下是 convertJsonToXml 的JUnit测试:

@Test
void convertJsonToXml() throws IOException, ParserConfigurationException, SAXException {
    try(InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("json/customer_sample.json")) {
        String json = new Scanner(in).useDelimiter("\\Z").next();
        String xml = converter.convertJsonToXml(json);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));
        Node first = doc.getFirstChild();
        assertNotNull(first);
        assertTrue(first.getChildNodes().getLength() > 0);
    }
}

答案 2 :(得分:1)

Android中没有可用于将JSON转换为XML的直接转换API。您需要首先解析JSON,然后您必须编写逻辑以将其转换为xml。

答案 3 :(得分:1)

标准org.json.XML类在两个方向上在JSON和XML之间进行转换。

转换不是很好,因为它根本不创建XML属性(仅限实体),因此XML输出比可能的更笨重。但它不需要定义与需要转换的数据结构匹配的Java类。

答案 4 :(得分:0)

Underscore-java库具有静态方法U.jsonToXml(string)。我是该项目的维护者。 Live example

import com.github.underscore.lodash.U;

public class MyClass {
    public static void main(String args[]) {
        String json = "{\"Price\": {"
        + "    \"LineItems\": {"
        + "        \"LineItem\": {"
        + "            \"UnitOfMeasure\": \"EACH\", \"Quantity\": 2, \"ItemID\": \"ItemID\""
        + "        }"
        + "    },"
        + "    \"Currency\": \"USD\","
        + "    \"EnterpriseCode\": \"EnterpriseCode\""
        + "}}";
        System.out.println(U.jsonToXml(json)); 
    }
}

输出:

<?xml version="1.0" encoding="UTF-8"?>
<Price>
  <LineItems>
    <LineItem>
      <UnitOfMeasure>EACH</UnitOfMeasure>
      <Quantity number="true">2</Quantity>
      <ItemID>ItemID</ItemID>
    </LineItem>
  </LineItems>
  <Currency>USD</Currency>
  <EnterpriseCode>EnterpriseCode</EnterpriseCode>
</Price>