`

xStream完美转换XML、JSON

 
阅读更多

xStream框架

xStream可以轻易的将Java对象和xml文档相互转换,而且可以修改某个特定的属性和节点名称,而且也支持json的转换;

前面有介绍过json-lib这个框架,在线博文:http://www.open-open.com/lib/view/open1327991992093.html

以及Jackson这个框架,在线博文:http://www.open-open.com/lib/view/open1327992553405.html

它们都完美支持JSON,但是对xml的支持还不是很好。一定程度上限制了对Java对象的描述,不能让xml完全体现到对Java对象的描述。这里将会介绍xStream对JSON、XML的完美支持。xStream不仅对XML的转换非常友好,而且提供annotation注解,可以在JavaBean 中完成对xml节点、属性的描述。以及对JSON也支持,只需要提供相关的JSONDriver就可以完成转换。

一、准备工作

1、 下载jar包、及官方资源

xStream的jar下载地址:

https://nexus.codehaus.org/content/repositories/releases/com/thoughtworks/xstream/xstream-distribution/1.3.1/xstream-distribution-1.3.1-bin.zip

官方的示例很全,官方参考示例:http://xstream.codehaus.org/tutorial.html

添加xstream-1.3.1.jar文件到工程中,就可以开始下面的工作;需要的jar如下:

 

2、 测试用例代码

 

/**
 * Java对象和XML字符串的相互转换
 */
public class XStreamTest {

	private XStream xstream = null;
	private ObjectOutputStream out = null;
	private ObjectInputStream in = null;
	private Student bean = null;
	
	/**
	 * 初始化资源准备
	 */
	@Before
	public void init() {
		try {
			xstream = new XStream();
			//xstream = new XStream(new DomDriver()); // 需要xpp3 jar
		} catch (Exception e) {
			e.printStackTrace();
		}
		bean = new Student();
		bean.setAddress("china");
		bean.setId(1);
		bean.setName("socfield");
		bean.setEmail("socfield@email.com");
		bean.setBirthday(new Date());
	}
	
	/**
	 * 释放对象资源
	 */
	@After
	public void destory() {
		xstream = null;
		bean = null;
		try {
			if (out != null) {
				out.flush();
				out.close();
			}
			if (in != null) {
				out.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.gc();
	}
	
	public final void fail(String string) {
		System.out.println(string);
	}
	
	public final void failRed(String string) {
		System.err.println(string);
	}
}

 

 

通过XStream对象的toXML方法就可以完成Java对象到XML的转换,toXML方法还有2个相同签名的方法,需要传递一个流。然后通过流来完成xml信息的输出。

 

3、 需要的JavaBean 

 

public class Student {
    private int id;
    private String name;
    private String email;
    private String address;
    private Birthday birthday;
    //getter、setter
    public String toString() {
        return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;
    }
}

 

 

二、Java转换成XML

 

1、 JavaBean转换XM

 

       /**
	 * Java对象转换成XML字符串
	 */
	@Test
	public void writeBean2XML() {
		try{
			fail("------Bean --> XML-----");
			fail(xstream.toXML(bean));
			fail("重命名后的XML");
			//类重命名
	        //xstream.alias("account", Student.class);
	        //xstream.alias("生日", Birthday.class);
	        //xstream.aliasField("生日", Student.class, "birthday");
	        //xstream.aliasField("生日", Birthday.class, "birthday");
	        //fail(xstream.toXML(bean));
	        //属性重命名
			xstream.aliasField("邮件", Student.class, "email");
			//包重命名
			xstream.aliasPackage("hoo","com.socfield.entity");
			fail(xstream.toXML(bean));
			
			} catch (Exception e) {
				e.printStackTrace();
			}
	}

 看结果中的第一份xml内容,是没有经过然后修改或重命名的文档,按照原样输出。文档中的第二份文档的  package经过重命名,email属性也经过重命名以及类名也可以进行重命名的。

 

运行后结果如下:

 

------Bean --> XML-----
<com.xstream.test.Student>
  <id>1</id>
  <name>socfield</name>
  <email>socfield@email.com</email>
  <address>china</address>
  <birthday>2015-05-09 16:34:19.23 CST</birthday>
</com.xstream.test.Student>
重命名后的XML
<com.xstream.test.Student>
  <id>1</id>
  <name>socfield</name>
  <邮件>socfield@email.com</邮件>
  <address>china</address>
  <birthday>2015-05-09 16:34:19.23 CST</birthday>
</com.xstream.test.Student>

 

 

2、 将List集合转换成xml文档

 

 

/**
	 * 将List集合转换成xml文档
	 */
	@Test
	public void writeList2XML() {
		try {
			//修改元素名称
			xstream.alias("beans", ListBean.class);
			xstream.alias("strdent",Student.class);
			
			ListBean listBean = new ListBean();
			listBean.setName("这是一个list集合");
			
			List<Object> list = new ArrayList<Object>();
			list.add(bean);
			list.add(bean);//引用bean
	        //list.add(listBean);//引用listBean,父元素
			
			bean = new Student();
			bean.setAddress("china");
	        bean.setEmail("tom@125.com");
	        bean.setId(2);
	        bean.setName("tom");
	        bean.setBirthday(new Date());
	        
	        list.add(bean);
	        listBean.setList(list);
	        //将ListBean中的集合设置空元素,即不显示集合元素标签
	        //xstream.addImplicitCollection(ListBean.class, "list");
	        
	        //设置reference模型
	        //xstream.setMode(XStream.NO_REFERENCES);//不引用
	        xstream.setMode(XStream.ID_REFERENCES);//id引用
	        //xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);//绝对路径引用
	          
	        //将name设置为父类(Student)的元素的属性
	        xstream.useAttributeFor(Student.class, "name");
	        //xstream.useAttributeFor(Birthday.class, "birthday");
	        //修改属性的name
	        xstream.aliasAttribute("姓名", "name");
	       // xstream.aliasField("生日", Birthday.class, "birthday");
	      
	        fail(xstream.toXML(listBean));
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	}

  

 

上面的代码运行后,结果如下:

 

<beans id="1">
  <name>这是一个list集合</name>
  <list id="2">
    <strdent id="3" 姓名="socfield">
      <id>1</id>
      <email>socfield@email.com</email>
      <address>china</address>
      <birthday id="4">2015-05-09 16:35:21.805 CST</birthday>
    </strdent>
    <strdent reference="3"/>
    <strdent id="5" 姓名="tom">
      <id>2</id>
      <email>tom@125.com</email>
      <address>china</address>
      <birthday id="6">2015-05-09 16:35:21.806 CST</birthday>
    </strdent>
  </list>
</beans>

 

 

如果不加xstream.addImplicitCollection(ListBean.class, "list");

这个设置的话,会出现一个List节点包裹着Student节点元素。添加addImplicitCollection可以忽略这个list节点元素。那么上面的list节点就不存在,只会在beans元素中出现name、student这2个xml元素标签;

setMode是设置相同的对象的引用方式,如果设置XStream.NO_REFERENCES就是不引用,会输出2分相同的 Student元素。如果是XStream.ID_REFERENCES会引用相同的那个对象的id属性,如果是 XStream.XPATH_ABSOLUTE_REFERENCES引用,那么它将显示xpath路径。上面采用的id引用,<student reference="3"/>这个引用了id=3的那个student标签元素;

useAttributeFor是设置某个节点显示到父节点的属性中,也就是将指定class中的指定属性,在这个class元素节点的属性中显示。

如:<student><name>hoojo</name></student>

设置好后就是这样的结果:<student name=”hoojo”></student>

aliasAttribute是修改属性名称。

 

3、 在JavaBean中添加Annotation注解进行重命名设置

 

先看看JavaBean的代码

 

import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamConverter;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
 
@XStreamAlias("class")
public class Classes {
    
    /*
     * 设置属性显示
     */
    @XStreamAsAttribute
    @XStreamAlias("名称")
    private String name;
    
    /*
     * 忽略
     */
    @XStreamOmitField
    private int number;
    
    @XStreamImplicit(itemFieldName = "Students")
    private List<Student> students;
    
    @SuppressWarnings("unused")
    @XStreamConverter(SingleValueCalendarConverter.class)
    private Calendar created = new GregorianCalendar();
 
    
    public Classes(){}
    public Classes(String name, Student... stu) {
        this.name = name;
        this.students = Arrays.asList(stu);
    }
    //getter、setter
}

 

 

SingleValueCalendarConverter.java这个是一个类型转换器

 

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
 
public class SingleValueCalendarConverter implements Converter {
     public void marshal(Object source, HierarchicalStreamWriter writer,
                MarshallingContext context) {
            Calendar calendar = (Calendar) source;
            writer.setValue(String.valueOf(calendar.getTime().getTime()));
        }
 
        public Object unmarshal(HierarchicalStreamReader reader,
                UnmarshallingContext context) {
            GregorianCalendar calendar = new GregorianCalendar();
            calendar.setTime(new Date(Long.parseLong(reader.getValue())));
            return calendar;
        }
 
        @SuppressWarnings("unchecked")
        public boolean canConvert(Class type) {
            return type.equals(GregorianCalendar.class);
        }
}

 

 

再看看测试用例代码

 

        /**
	 * 在JavaBean中添加Annotation注解进行重命名设置
	 */
	@Test
	public void WriterList2XML4Annotation() {
		try {
			failRed("---------annotation Bean --> XML---------");
			Student stu = new Student();
			stu.setName("jack");
			Classes c = new Classes("一班",bean,stu);
			c.setNumber(2);
			//对指定的类使用Annotation
	        //xstream.processAnnotations(Classes.class);
	        //启用Annotation
	        //xstream.autodetectAnnotations(true);
	        xstream.alias("student", Student.class);
	        fail(xstream.toXML(c));
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	}

 当启用annotation或是对某个特定的类启用annotation时,上面的classes这个类才有效果。如果不启用annotation,运行后结果如下:

 

 

 

---------annotation Bean --> XML---------
<com.xstream.test.Classes>
  <name>一班</name>
  <number>2</number>
  <students class="java.util.Arrays$ArrayList">
    <a class="student-array">
      <student>
        <id>1</id>
        <name>socfield</name>
        <email>socfield@email.com</email>
        <address>china</address>
        <birthday>2015-05-09 16:37:07.339 CST</birthday>
      </student>
      <student>
        <id>0</id>
        <name>jack</name>
      </student>
    </a>
  </students>
  <created>
    <time>1431160627346</time>
    <timezone>Asia/Shanghai</timezone>
  </created>
</com.xstream.test.Classes>

 

 

 当启用annotation后xstream.processAnnotations(Classes.class),结果如下:

 

---------annotation Bean --> XML---------
<class 名称="一班">
  <Students>
    <id>1</id>
    <name>socfield</name>
    <email>socfield@email.com</email>
    <address>china</address>
    <birthday>2015-05-09 16:44:41.742 CST</birthday>
  </Students>
  <Students>
    <id>0</id>
    <name>jack</name>
  </Students>
  <created>1431161081748</created>
</class>

 

 

 4、 Map集合转换xml文档

 

 

        /**
	 * Map集合转换xml文档
	 * Java Map集合转XML
	 */
	@Test
	public void writeMap2XML() {
		try {
			
			failRed("---------Map --> XML---------");
	        Map<String, Student> map = new HashMap<String, Student>();
	        map.put("No.1", bean);//put
	        
	        bean = new Student();
	        bean.setAddress("china");
	        bean.setEmail("tom@125.com");
	        bean.setId(2);
	        bean.setName("tom");
	        bean.setBirthday(new Date());
	        map.put("No.2", bean);//put
	        
	        bean = new Student();
	        bean.setName("jack");
	        map.put("No.3", bean);//put
	        
	        xstream.alias("student", Student.class);
	        xstream.alias("key", String.class);
	        xstream.useAttributeFor(Student.class, "id");
	        xstream.useAttributeFor("birthday", String.class);
	        fail(xstream.toXML(map));
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	}

 

 

运行后结果如下:

 

---------Map --> XML---------
<map>
  <entry>
    <key>No.3</key>
    <student id="0">
      <name>jack</name>
    </student>
  </entry>
  <entry>
    <key>No.1</key>
    <student id="1">
      <name>socfield</name>
      <email>socfield@email.com</email>
      <address>china</address>
      <birthday>2015-05-09 16:37:49.763 CST</birthday>
    </student>
  </entry>
  <entry>
    <key>No.2</key>
    <student id="2">
      <name>tom</name>
      <email>tom@125.com</email>
      <address>china</address>
      <birthday>2015-05-09 16:37:49.763 CST</birthday>
    </student>
  </entry>
</map>

 

 

5、 用OutStream输出流写XML

 

 

        /**
	 * 用OutStream输出流写XML
	 */
	@Test
	public void writeXML4OutStream() {
		try {
			out = xstream.createObjectOutputStream(System.out);
			Student stu = new Student();
			stu.setName("jack");
	        Classes c = new Classes("一班", bean, stu);
	        c.setNumber(2);
	        failRed("---------ObjectOutputStream # JavaObject--> XML---------");
	        out.writeObject(stu);
	        out.writeObject(new Date());
	        out.write(22);//byte
	        out.writeBoolean(true);
	        out.writeFloat(22.f);
	        out.writeUTF("hello");
	        
		} catch (Exception e) {
	        e.printStackTrace();
	    }
	}

 

 

 使用输出流后,可以通过流对象完成xml的构建,即使没有JavaBean对象,你可以用流来构建一个复杂的xml文档,运行后结果如下:

 

 

---------ObjectOutputStream # JavaObject--> XML---------
<object-stream>
  <com.xstream.test.Student>
    <id>0</id>
    <name>jack</name>
  </com.xstream.test.Student>
  <date>2015-05-09 16:38:35.377 CST</date>
  <byte>22</byte>
  <boolean>true</boolean>
  <float>22.0</float>
  <string>hello</string>
</object-stream>

 

 

三、XML内容转换Java对象

 

1、 用InputStream将XML文档转换成java对象

/**
 * 用InputStream将XML文档转换成java对象
 * 需要额外的jar xpp3-main.jar
 */

@Test
public void readXML4InputStream() {
	try {
		
		xstream = new XStream(new DomDriver()); // 需要xpp3 jar
		
		String s = "<object-stream><com.xstream.test.Student><id>0</id><name>jack</name>" +
		          "</com.xstream.test.Student>" +
		          "<byte>22</byte><boolean>true</boolean><float>22.0</float>" +
		          "<string>hello</string></object-stream>";
		        failRed("---------ObjectInputStream## XML --> javaObject---------");
		        StringReader reader = new StringReader(s);
		        in = xstream.createObjectInputStream(reader);
		        Student stu = (Student) in.readObject();
		       // Birthday b = (Birthday) in.readObject();
		        byte i = in.readByte();
		        boolean bo = in.readBoolean();
		        float f = in.readFloat();
		        String str = in.readUTF();
		        System.out.println(stu);
		       // System.out.println(b);
		        System.out.println(i);
		        System.out.println(bo);
		        System.out.println(f);
		        System.out.println(str);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

 

 

读取后,转换的Java对象,结果如下:

---------ObjectInputStream## XML --> javaObject---------
#0#null#null
22
true
22.0
hello

 

2、 将xml文档转换成Java对象 

/**
 *  将xml文档转换成Java对象
 */

@Test
public void readXML2Object() {
	try {
		
		xstream = new XStream(new DomDriver()); // 需要xpp3 jar
		
		failRed("-----------Xml >>> Bean--------------");
        Student stu = (Student) xstream.fromXML(xstream.toXML(bean));
        fail(stu.toString());
        
        List<Student> list = new ArrayList<Student>();
        list.add(bean);//add
        
        Map<String, Student> map = new HashMap<String, Student>();
        map.put("No.1", bean);//put
        
        bean = new Student();
        bean.setAddress("china");
        bean.setEmail("tom@125.com");
        bean.setId(2);
        bean.setName("tom");
        Date day = new Date();
        bean.setBirthday(day);
        list.add(bean);//add
        map.put("No.2", bean);//put
        
        bean = new Student();
        bean.setName("jack");
        list.add(bean);//add
        map.put("No.3", bean);//put
        
        failRed("==========XML >>> List===========");
        List<Student> studetns = (List<Student>) xstream.fromXML(xstream.toXML(list));
        fail("size:" + studetns.size());//3
        for (Student s : studetns) {
            fail(s.toString());
        }
        
        failRed("==========XML >>> Map===========");
        Map<String, Student> maps = (Map<String, Student>) xstream.fromXML(xstream.toXML(map));
        fail("size:" + maps.size());//3
        Set<String> key = maps.keySet();
        Iterator<String> iter = key.iterator();
        while (iter.hasNext()) {
            String k = iter.next();
            fail(k + ":" + map.get(k));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

 

 运行后结果如下:

-----------Xml >>> Bean--------------
==========XML >>> List===========#1#china#socfield@email.com

size:3
#1#china#socfield@email.com
#2#china#tom@125.com
#0#null#null
==========XML >>> Map===========
size:3
No.3:#0#null#null
No.1:#1#china#socfield@email.com
No.2:#2#china#tom@125.com

 

怎么样,成功的完成XML到JavaBean、List、Map的转换,更多对象转换还需要大家一一尝试。用法类似~这里就不一样赘述。

 

四、XStream对JSON的支持

 

xStream对JSON也有非常好的支持,它提供了2个模型驱动。用这2个驱动可以完成Java对象到JSON的相互转换。使用JettisonMappedXmlDriver驱动,将Java对象转换成json,需要添加jettison.jar

 

1、 用JettisonMappedXmlDriver完成Java对象到JSON的转换

/**
 *  用JettisonMappedXmlDriver完成Java对象到JSON的转换
 *  需添加 jettison jar
 */
@Test
public void writeEntity2JEETSON() {
	failRed("=======JettisonMappedXmlDriver===JavaObject >>>> JaonString=========");
    xstream = new XStream(new JettisonMappedXmlDriver());
    xstream.setMode(XStream.NO_REFERENCES);
    xstream.alias("student", Student.class);
    fail(xstream.toXML(bean));
}

 

 运行后结果如下:

=======JettisonMappedXmlDriver===JavaObject >>>> JaonString=========
{"student":{"id":1,"name":"socfield","email":"socfield@email.com","address":"china","birthday":"2015-05-09 16:52:25.988 CST"}}

 

JSON的转换和XML的转换用法一样,只是创建XStream需要传递一个参数,这个参数就是xml到JSON映射转换的驱动。这里会降到两个驱动,分别是JettisonMappedXmlDriver、JsonHierarchicalStreamDriver。

 

2、 JsonHierarchicalStreamDriver完成Java对象到JSON的转换 

/**
 * 用XStream结合JsonHierarchicalStreamDriver驱动
 * 转换java对象为JSON字符串
 */

@Test
public void writeEntity2JSON() {
	failRed("======JsonHierarchicalStreamDriver====JavaObject >>>> JaonString=========");
	xstream = new XStream(new JsonHierarchicalStreamDriver());
    //xstream.setMode(XStream.NO_REFERENCES);
    xstream.alias("student", Student.class);
    failRed("-------Object >>>> JSON---------");
    fail(xstream.toXML(bean));
    
    //failRed("========JsonHierarchicalStreamDriver==删除根节点=========");
    //删除根节点
    xstream = new XStream(new JsonHierarchicalStreamDriver() {
        public HierarchicalStreamWriter createWriter(Writer out) {
            return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE);
        }
    });
    //xstream.setMode(XStream.NO_REFERENCES);
    xstream.alias("student", Student.class);
    fail(xstream.toXML(bean));
	
}

 

运行后结果如下:

 

======JsonHierarchicalStreamDriver====JavaObject >>>> JaonString=========
-------Object >>>> JSON---------
{"student": {
  "id": 1,
  "name": "socfield",
  "email": "socfield@email.com",
  "address": "china",
  "birthday": "2015-05-09 16:53:56.250 CST"
}}
{
  "id": 1,
  "name": "socfield",
  "email": "socfield@email.com",
  "address": "china",
  "birthday": "2015-05-09 16:53:56.250 CST"
}

 

使用JsonHierarchicalStreamDriver转换默认会给转换后的对象添加一个根节点,但是在构建JsonHierarchicalStreamDriver驱动的时候,你可以重写createWriter方法,删掉根节点。

看上面的结果,一个是默认带根节点的JSON对象,它只是将类名作为一个属性,将对象作为该属性的一个值。而另一个没有带根属性的JSON就是通过重写createWriter方法完成的。

 

 

3、 将List集合转换成JSON字符串

/**
 * 将List集合转换成JSON字符串
 */
@Test
public void writerList2JSON() {
	failRed("======JsonHierarchicalStreamDriver====JavaObject >>>> JaonString=========");
	JsonHierarchicalStreamDriver driver = new JsonHierarchicalStreamDriver();
    xstream = new XStream(driver);
    //xstream = new XStream(new JettisonMappedXmlDriver());//转换错误
    //xstream.setMode(XStream.NO_REFERENCES);
    xstream.alias("student", Student.class);
    
    List<Student> list = new ArrayList<Student>();
    list.add(bean);//add
    
    bean = new Student();
    bean.setAddress("china");
    bean.setEmail("tom@125.com");
    bean.setId(2);
    bean.setName("tom");
    Date day = new Date();
    bean.setBirthday(day);
    list.add(bean);//add
    
    bean = new Student();
    bean.setName("jack");
    list.add(bean);//add
    
    fail(xstream.toXML(list));
    
    //failRed("========JsonHierarchicalStreamDriver==删除根节点=========");
    //删除根节点
	
    xstream = new XStream(new JsonHierarchicalStreamDriver() {
    	public HierarchicalStreamWriter createWriter(Writer out) {
    		return new JsonWriter(out,JsonWriter.DROP_ROOT_MODE);
    	}
    });
    xstream.alias("student", Student.class);
    fail(xstream.toXML(list));
}

 

运行后结果如下

======JsonHierarchicalStreamDriver====JavaObject >>>> JaonString=========
{"list": [
  {
    "id": 1,
    "name": "socfield",
    "email": "socfield@email.com",
    "address": "china",
    "birthday": "2015-05-09 16:55:24.558 CST"
  },
  {
    "id": 2,
    "name": "tom",
    "email": "tom@125.com",
    "address": "china",
    "birthday": "2015-05-09 16:55:24.562 CST"
  },
  {
    "id": 0,
    "name": "jack"
  }
]}
[
  {
    "id": 1,
    "name": "socfield",
    "email": "socfield@email.com",
    "address": "china",
    "birthday": "2015-05-09 16:55:24.558 CST"
  },
  {
    "id": 2,
    "name": "tom",
    "email": "tom@125.com",
    "address": "china",
    "birthday": "2015-05-09 16:55:24.562 CST"
  },
  {
    "id": 0,
    "name": "jack"
  }
]

  

上面的list1是使用JsonHierarchicalStreamDriver 转换的,当然你也可以使用JettisonMappedXmlDriver驱动进行转换;用JettisonMappedXmlDriver转换后,你会发现格式不同而且没有根属性。

 

4、 Map转换json

/**
 * Map转换json
 */
@Test
public void writeMap2JSON() {
	 failRed("======JsonHierarchicalStreamDriver==== Map >>>> JaonString=========");
	    xstream = new XStream(new JsonHierarchicalStreamDriver());
	    //xstream = new XStream(new JettisonMappedXmlDriver());
	    xstream.alias("student", Student.class);
	
	Map<String,Student> map = new HashMap<String,Student>();
	map.put("No.1", bean);
	
	 bean = new Student();
	    bean.setAddress("china");
	    bean.setEmail("tom@125.com");
	    bean.setId(2);
	    bean.setName("tom");
	    bean.setBirthday(new Date());
	    map.put("No.2", bean);//put
	    
	    bean = new Student();
	    bean.setName("jack");
	    map.put("No.3", bean);//put
	    
	    fail(xstream.toXML(map));
	    
	    //failRed("========JsonHierarchicalStreamDriver==删除根节点=========");
	    //删除根节点
	    xstream = new XStream(new JsonHierarchicalStreamDriver() {
	        public HierarchicalStreamWriter createWriter(Writer out) {
	            return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE);
	        }
	    });
	    xstream.alias("student", Student.class);
	    fail(xstream.toXML(map));
	
}

 

运行后结果如下:

======JsonHierarchicalStreamDriver==== Map >>>> JaonString=========
{"map": [
  [
    "No.3",
    {
      "id": 0,
      "name": "jack"
    }
  ],
  [
    "No.1",
    {
      "id": 1,
      "name": "socfield",
      "email": "socfield@email.com",
      "address": "china",
      "birthday": "2015-05-09 16:56:41.361 CST"
    }
  ],
  [
    "No.2",
    {
      "id": 2,
      "name": "tom",
      "email": "tom@125.com",
      "address": "china",
      "birthday": "2015-05-09 16:56:41.364 CST"
    }
  ]
]}
[
  [
    "No.3",
    {
      "id": 0,
      "name": "jack"
    }
  ],
  [
    "No.1",
    {
      "id": 1,
      "name": "socfield",
      "email": "socfield@email.com",
      "address": "china",
      "birthday": "2015-05-09 16:56:41.361 CST"
    }
  ],
  [
    "No.2",
    {
      "id": 2,
      "name": "tom",
      "email": "tom@125.com",
      "address": "china",
      "birthday": "2015-05-09 16:56:41.364 CST"
    }
  ]
]

  

5、 将JSON转换java对象

/**
 * JsonHierarchicalStreamDriver可以将简单的json字符串转换成java对象,list、map转换不成功;
 * JsonHierarchicalStreamDriver读取JSON字符串到java对象出错
 */
@Test
public void readJSON2Object() throws JSONException {
	 String json = "{\"student\": {" +
		        "\"id\": 1," +
		        "\"name\": \"haha\"," +
		        "\"email\": \"email\"," +
		        "\"address\": \"address\"," +
		            "\"birthday\": \"2015-05-09 16:12:46.695 CST\"" +
		    "}}";
	 
	//JsonHierarchicalStreamDriver读取JSON字符串到java对象出错,但JettisonMappedXmlDriver可以
	    xstream = new XStream(new JettisonMappedXmlDriver());
	    xstream.alias("student", Student.class);
	    fail(xstream.fromXML(json).toString());
	    
	    //JettisonMappedXmlDriver转换List集合出错,但JsonHierarchicalStreamDriver可以转换正确
	    //JettisonMappedXmlDriver 转换的字符串 {"list":{"student":[{"id":1,"name":"haha","email":"email","address":"address","birthday":[{},"2010-11-22"]}]},"student":{"id":2,"name":"tom","email":"tom@125.com","address":"china","birthday":[{},"2010-11-22"]}}
	    json = "{\"list\": [{" +
	            "\"id\": 1," +
	            "\"name\": \"haha\"," +
	            "\"email\": \"email\"," +
	            "\"address\": \"address\"," +
	              "\"birthday\": \"2015-05-09 16:12:46.695 CST\"" +
	           "},{" +
	            "\"id\": 2," +
	            "\"name\": \"tom\"," +
	            "\"email\": \"tom@125.com\"," +
	            "\"address\": \"china\"," +
	              "\"birthday\": \"2015-05-09 16:12:46.695 CST\"" +
	          "}]}";
	    System.out.println(json);//用js转换成功
	    List list = (List) xstream.fromXML(json);
	    System.out.println(list.size());//0好像转换失败
}

 运行后结果如下:

#1#address#email
{"list": [{"id": 1,"name": "haha","email": "email","address": "address","birthday": "2015-05-09 16:12:46.695 CST"},
{"id": 2,"name": "tom","email": "tom@125.com","address": "china","birthday": "2015-05-09 16:12:46.695 CST"}]}
0

 JSON到Java的转换是fromXML方法。

 

 

 

 

 

 

 

 

 

 

 

 

 

来自:http://www.cnblogs.com/hoojo/archive/2011/04/22/2025197.html

 

分享到:
评论

相关推荐

    转载 xStream完美转换XML、JSON

    标题 "xStream完美转换XML、JSON" 指的是使用xStream库在Java中进行XML与JSON数据格式之间的转换。xStream是一个强大的库,它提供了一种简单的方式来序列化和反序列化Java对象到XML,反之亦然。在这个场景中,它同样...

    xStream转换xml和json源码

    本篇文章将深入探讨xStream如何实现Java对象与XML和JSON的相互转换,并提供详细的代码示例。 ### 1. xStream的安装与引入 首先,你需要在项目中添加xStream的依赖。如果你使用的是Maven,可以在pom.xml文件中添加...

    《xStream完美转换XML、JSON》学习笔记

    《xStream完美转换XML、JSON》学习笔记 在IT领域,数据交换是常见的需求,而XML和JSON作为两种广泛使用的数据格式,它们之间的转换尤为重要。xStream是一个强大的Java库,它能够轻松地将Java对象序列化为XML或反...

    xStream完美转换XML.docx

    【xStream 框架详解:Java对象与XML、JSON的完美转换】 xStream是一个强大的Java库,它提供了简单易用的API,用于将Java对象序列化为XML,以及将XML反序列化回Java对象。此外,xStream还支持JSON格式的转换。这个...

    xstream将xml文档转换成json对象

    在这个场景中,我们将探讨如何使用XStream将XML文档转换成Java对象,进而转化为JSON对象。 首先,我们需要引入XStream库。XStream的核心功能是能够将Java对象和XML之间的映射自动化,极大地简化了序列化和反序列化...

    XStream XML与Json转换

    XStream在运行时使用Java反射机制对要进行序列化的对象树的结构进行探索,并不需要对对象作出修改。...XStream在进行数据类型转换时,使用系统缺省的类型转换器。同时,也支持用户自定义的类型转换器。

    Xstream 类与Json之间转换

    Xstream和Json是两种广泛使用的工具,分别用于Java对象到XML和JSON格式的转换。本文将深入探讨Xstream库如何与Json进行交互,以及在实际应用中的使用。 Xstream是一个Java库,它提供了简单、高效的方式来序列化和反...

    XStream在JavaBean与XML/JSON 之间相互转换

    **XStream:JavaBean与XML/JSON之间的转换大师** XStream是一个开源库,它为Java对象提供了简单且直观的XML序列化和反序列化的解决方案。它不仅能够将Java对象转换成XML,反之亦然,还能支持JSON格式的转换。这个...

    Xstream操作Xml与Json.doc

    Xstream 是一个 Java 库,用于处理 XML 文件的序列化和反序列化,同时也支持将 JavaBean 转换为 JSON 格式。它的核心理念是通过简单的 API 设计,使得 XML 序列化过程变得简洁,无需额外的映射文件或辅助类。 ### 1...

    xml解析及使用XStream实现javaBean与xml之间的转换

    在`xmlAnalysis`文件夹中,可能包含了一个简单的Java程序,演示了如何使用DOM、SAX、StAX和XStream解析XML文件,并展示了XStream如何在JavaBean与XML之间进行转换。你可以运行这些代码,观察输出结果,以加深理解。...

    xml & json 转换工具

    在这个上下文中,它可能被用来帮助转换XML对象到JSON对象,或者相反的过程。 2. **json-lib-2.2.3-jdk13.jar**:这是一个JSON库,提供了多种Java版本的支持。Json-lib可以解析JSON字符串,创建JSON对象,并且能将...

    xml 与json转换代码

    在Java中,可以使用各种库来实现XML到JSON的转换,其中XStream是一个流行的库,它提供了强大的XML序列化和反序列化功能。XStream虽然主要设计用来XML操作,但也可以通过添加额外的转换器来处理JSON。首先,你需要...

    使用XStream是实现XML与Java对象的转换(5)--Object Stream

    XStream是一个强大的库,它使得XML与Java对象之间的转换变得简单。在这个主题中,我们将深入探讨如何使用XStream进行XML与Java对象的互换,并了解其工作原理。 首先,XStream是一个开源库,由Johannes Leutenegger...

    XStream转换

    在本文中,我们将深入探讨XStream的工作原理、如何使用它来实现bean到XML、XML到bean以及XML到JSON的转换,并给出相关示例。 首先,让我们了解XStream的基本概念。XStream的核心功能是通过反射机制将Java对象转换为...

    XML、JAVA、JSON多种方式互相转换

    - Google的Gson库可以通过第三方扩展如`com.thoughtworks.xstream:xstream`实现JSON到XML的转换。 3. Java对象到XML和JSON: - JAXB允许直接将Java对象转换为XML,反之亦然。通过创建对应的Java类并使用`...

    使用XStream是实现XML与Java对象的转换(4)--转换器

    这就是XStream转换器的作用。 转换器分为两种类型:LocalConverter和HierarchicalStreamConverter。LocalConverter仅对特定的域对象实例进行转换,而HierarchicalStreamConverter则可以处理整个XML层级结构。 1. *...

    Xstream for Json 完整范例(绝对好用)

    现在,你可以使用Xstream的`toXML()`方法将Java对象转换为JSON字符串,或者使用`fromXML()`方法将JSON字符串反序列化为Java对象。例如,假设我们有一个名为`Employee`的Java类,我们可以这样做: ```java Employee ...

    json XStream

    通过结合XStream和Jettison,开发者可以在Java应用中实现XML和JSON的无缝转换。 首先,我们需要在项目中引入XStream和Jettison的依赖。在本例中,我们有`xstream-1.3.1.jar`和`jettison-1.0.1.jar`。这两个JAR文件...

Global site tag (gtag.js) - Google Analytics