Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

java - Simplest method to Convert Json to Xml

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For a simple solution, I recommend Jackson, as it can transform arbitrarily complex JSON into XML with just a few simple lines of code.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...