I have web-service in .net. When I retrieve data from database, it returns JSON File in Android Mobile. How can I convert JSON File to XML Or text.
我在。net上有网络服务。当我从数据库中检索数据时,它会在Android Mobile中返回JSON文件。如何将JSON文件转换为XML或文本。
4 个解决方案
#1
7
For a simple solution, I recommend Jackson, as it can transform arbitrarily complex JSON into XML with just a few simple lines of code.
对于简单的解决方案,我推荐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;
}
This demo uses Jackson 1.7.7 (the newer 1.7.8 should also work), Jackson XML Databind 0.5.3 (not yet compatible with Jackson 1.8), and Stax2 3.1.1.
这个演示使用Jackson 1.7.7(更新的1.7.8也可以)、Jackson XML Databind 0.5.3(还不能与Jackson 1.8兼容)和Stax2 3.1.1。
#2
2
Here is an example of how you can do this, generating valid XML. I also use the Jackson library in a Maven project.
下面是一个示例,演示如何生成有效的XML。我还在Maven项目中使用Jackson库。
Maven setup:
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>
Here is some Java code that first converts a JSON string to an object and then converts the object with the XMLMapper to XML and also removes any wrong element names. The reason for replacing wrong characters in XML element names is the fact that you can use in JSON element names like $oid with characters not allowed in XML. The Jackson library does not account for that, so I ended up adding some code which removes illegal characters from element names and also the namespace declarations.
下面是一些Java代码,它们首先将JSON字符串转换为对象,然后使用XMLMapper将对象转换为XML,并删除任何错误的元素名称。在XML元素名称中替换错误字符的原因是可以在JSON元素名称(如$oid)中使用XML中不允许的字符。Jackson库没有对此进行说明,因此我最后添加了一些代码,从元素名称和名称空间声明中删除非法字符。
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));
}
}
Here is a JUnit test for convertJsonToXml:
下面是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);
}
}
#3
1
No direct conversion API is available in android to convert JSON to XML. You need to parse JSON first then you will have to write logic for converting it to xml.
android中没有直接转换API来将JSON转换为XML。首先需要解析JSON,然后必须编写将其转换为xml的逻辑。
#4
1
Standard org.json.XML class converts between JSON and XML in both directions.
标准org.json。XML类在JSON和XML之间双向转换。
The conversion is not very nice as it does not create XML attributes at all (entities only), so XML output is more bulky than could possibly be. But it does not require to define Java classes matching the data structures that need to be converted.
转换不是很好,因为它根本不创建XML属性(仅创建实体),所以XML输出比可能的要大。但是不需要定义与需要转换的数据结构相匹配的Java类。
#1
7
For a simple solution, I recommend Jackson, as it can transform arbitrarily complex JSON into XML with just a few simple lines of code.
对于简单的解决方案,我推荐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;
}
This demo uses Jackson 1.7.7 (the newer 1.7.8 should also work), Jackson XML Databind 0.5.3 (not yet compatible with Jackson 1.8), and Stax2 3.1.1.
这个演示使用Jackson 1.7.7(更新的1.7.8也可以)、Jackson XML Databind 0.5.3(还不能与Jackson 1.8兼容)和Stax2 3.1.1。
#2
2
Here is an example of how you can do this, generating valid XML. I also use the Jackson library in a Maven project.
下面是一个示例,演示如何生成有效的XML。我还在Maven项目中使用Jackson库。
Maven setup:
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>
Here is some Java code that first converts a JSON string to an object and then converts the object with the XMLMapper to XML and also removes any wrong element names. The reason for replacing wrong characters in XML element names is the fact that you can use in JSON element names like $oid with characters not allowed in XML. The Jackson library does not account for that, so I ended up adding some code which removes illegal characters from element names and also the namespace declarations.
下面是一些Java代码,它们首先将JSON字符串转换为对象,然后使用XMLMapper将对象转换为XML,并删除任何错误的元素名称。在XML元素名称中替换错误字符的原因是可以在JSON元素名称(如$oid)中使用XML中不允许的字符。Jackson库没有对此进行说明,因此我最后添加了一些代码,从元素名称和名称空间声明中删除非法字符。
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));
}
}
Here is a JUnit test for convertJsonToXml:
下面是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);
}
}
#3
1
No direct conversion API is available in android to convert JSON to XML. You need to parse JSON first then you will have to write logic for converting it to xml.
android中没有直接转换API来将JSON转换为XML。首先需要解析JSON,然后必须编写将其转换为xml的逻辑。
#4
1
Standard org.json.XML class converts between JSON and XML in both directions.
标准org.json。XML类在JSON和XML之间双向转换。
The conversion is not very nice as it does not create XML attributes at all (entities only), so XML output is more bulky than could possibly be. But it does not require to define Java classes matching the data structures that need to be converted.
转换不是很好,因为它根本不创建XML属性(仅创建实体),所以XML输出比可能的要大。但是不需要定义与需要转换的数据结构相匹配的Java类。