使用jaxkson将对象转换成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;
}

猜你喜欢

转载自blog.csdn.net/weixin_43944305/article/details/112660590