jackson、Gson、xmlpull、xmlbeans、dom4j、jdom等。这些库提供了各种将XML和JSON字符串互相转换的方法 在java中的使用方式
时间: 2023-07-10 08:43:02 浏览: 90
这些库都提供了各种将XML和JSON字符串互相转换的方法,具体使用方式如下:
1. Jackson:
- 将Java对象转换为JSON字符串:
```
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(myObject);
```
- 将JSON字符串转换为Java对象:
```
ObjectMapper objectMapper = new ObjectMapper();
MyObject myObject = objectMapper.readValue(json, MyObject.class);
```
2. Gson:
- 将Java对象转换为JSON字符串:
```
Gson gson = new Gson();
String json = gson.toJson(myObject);
```
- 将JSON字符串转换为Java对象:
```
Gson gson = new Gson();
MyObject myObject = gson.fromJson(json, MyObject.class);
```
3. xmlpull:
- 将XML字符串转换为Java对象:
```
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(xml));
MyObject myObject = new MyObject();
while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
if (xpp.getEventType() == XmlPullParser.START_TAG && xpp.getName().equals("myField")) {
myObject.setMyField(xpp.nextText());
}
xpp.next();
}
```
- 将Java对象转换为XML字符串:
```
StringWriter writer = new StringWriter();
XmlSerializer serializer = Xml.newSerializer();
serializer.setOutput(writer);
serializer.startDocument("UTF-8", true);
serializer.startTag("", "myObject");
serializer.startTag("", "myField");
serializer.text(myObject.getMyField());
serializer.endTag("", "myField");
serializer.endTag("", "myObject");
serializer.endDocument();
String xml = writer.toString();
```
4. xmlbeans:
- 将XML字符串转换为Java对象:
```
XmlObject xmlObject = XmlObject.Factory.parse(xml);
MyObject myObject = MyObject.Factory.parse(xmlObject.newInputStream());
```
- 将Java对象转换为XML字符串:
```
MyObject myObject = MyObject.Factory.newInstance();
myObject.setMyField("myValue");
String xml = myObject.xmlText();
```
5. dom4j:
- 将XML字符串转换为Java对象:
```
Document document = DocumentHelper.parseText(xml);
Element root = document.getRootElement();
MyObject myObject = new MyObject();
myObject.setMyField(root.element("myField").getText());
```
- 将Java对象转换为XML字符串:
```
MyObject myObject = new MyObject();
myObject.setMyField("myValue");
Document document = DocumentHelper.createDocument();
Element root = document.addElement("myObject");
Element myField = root.addElement("myField");
myField.setText(myObject.getMyField());
String xml = document.asXML();
```
6. jdom:
- 将XML字符串转换为Java对象:
```
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new StringReader(xml));
Element root = document.getRootElement();
MyObject myObject = new MyObject();
myObject.setMyField(root.getChildText("myField"));
```
- 将Java对象转换为XML字符串:
```
MyObject myObject = new MyObject();
myObject.setMyField("myValue");
Element root = new Element("myObject");
Element myField = new Element("myField");
myField.setText(myObject.getMyField());
root.addContent(myField);
Document document = new Document(root);
XMLOutputter outputter = new XMLOutputter();
String xml = outputter.outputString(document);
```
阅读全文