Simplest method to Convert Json to Xml

前端 未结 5 1621
挽巷
挽巷 2020-12-06 05:12

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.

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-06 06:00

    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));
        // FOO42
      }
    }
    
    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.

提交回复
热议问题