1、首先下载 xstream.jar和jettison.jar(转换为json时用到),并引入该包。 2、看如下代码吧: import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver; import com.thoughtworks.xstream.io.xml.DomDriver; public class Student { private String name; private String sex; /* * 构造函数 */ public Student(String name, String sex) { this.name = name; this.sex = sex; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } /* * 对象转换为 xml * @return String */ public String toXml() { XStream xStream = new XStream(new DomDriver()); return xStream.toXML(this); } /* * 对象转换为json * @return String */ public String toJson() { XStream xStream = new XStream(new JettisonMappedXmlDriver()); return xStream.toXML(this); } /* * xml类转换为对象 * @param String * @return Student */ public Student toXmlObject(String xml) { XStream xStream = new XStream(new DomDriver()); return (Student) xStream.fromXML(xml); } /* * json转换为对象 * @param String * @return Student */ public Student toJsonObject(String xml) { XStream xStream = new XStream(new JettisonMappedXmlDriver()); return (Student) xStream.fromXML(xml); } public static void main(String[] arge) throws IOException { Student student = new Student("张三", "男"); File file = new File("d:/student.xml"); // xml: 输出 转换为 xml FileUtils.writeStringToFile(file, student.toXml()); // xml: 输入转换为对象 String in = FileUtils.readFileToString(file); Student st = student.toXmlObject(in); // json: 输出 转换为json FileUtils.writeStringToFile(file, student.toJson()); // json: 输入转换为对象 in = FileUtils.readFileToString(file); st = student.toJsonObject(in); } }