java实现Xml与json之间的相互转换操作示例

发布时间:2020-09-30 00:58:30 作者:horizon~~~
来源:脚本之家 阅读:455

本文实例讲述了java实现Xml与json之间的相互转换操作。分享给大家供大家参考,具体如下:

旁白:

最近关于xml与json之间的转换都搞蒙了,这里写一个demo,以后备用。

正题:

project格式是:

java实现Xml与json之间的相互转换操作示例

jar包是一个一个检出来的,还算干净了。

代码:

工具类:

package exercise.xml;
import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.xml.XMLSerializer;
import org.jdom.Document;
public class XmlExercise {
  /**
   * 将xml字符串<STRONG>转换</STRONG>为JSON字符串
   *
   * @param xmlString
   *      xml字符串
   * @return JSON<STRONG>对象</STRONG>
   */
  public static String xml2json(String xmlString) {
    XMLSerializer xmlSerializer = new XMLSerializer();
    JSON json = xmlSerializer.read(xmlString);
    return json.toString(1);
  }
  /**
   * 将xmlDocument<STRONG>转换</STRONG>为JSON<STRONG>对象</STRONG>
   *
   * @param xmlDocument
   *      XML Document
   * @return JSON<STRONG>对象</STRONG>
   */
  public static String xml2json(Document xmlDocument) {
    return xml2json(xmlDocument.toString());
  }
  /**
   * JSON(数组)字符串<STRONG>转换</STRONG>成XML字符串
   *
   * @param jsonString
   * @return
   */
  public static String json2xml(String jsonString) {
    XMLSerializer xmlSerializer = new XMLSerializer();
    return xmlSerializer.write(JSONSerializer.toJSON(jsonString));
    // return xmlSerializer.write(JSONArray.fromObject(jsonString));//这种方式只支持JSON数组
  }
}

测试类:

package exercise.xml;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class XmlTest extends XmlExercise {
  public static void main(String[] args) {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("username", "horizon");
    JSONArray jsonArray = new JSONArray();
    JSONObject dataJson = new JSONObject();
    jsonArray.add(jsonObject);
    //jsonArray.add(jsonObject);
    dataJson.put("data", jsonArray);
    System.out.println(dataJson.toString());
    String xml = json2xml(dataJson.toString());
    System.out.println("xml:" + xml);
    String str = xml2json(xml);
    System.out.println("to_json" + str);
  }
}

PS:这里再为大家提供几款相关在线工具供大家参考使用:

在线JSON代码检验、检验、美化、格式化工具:
http://tools.jb51.net/code/json

在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson

在线格式化XML/在线压缩XML
http://tools.jb51.net/code/xmlformat

XML在线压缩/格式化工具:
http://tools.jb51.net/code/xml_format_compress

XML代码在线格式化美化工具:
http://tools.jb51.net/code/xmlcodeformat

更多关于java算法相关内容感兴趣的读者可查看本站专题:《Java操作json格式数据技巧总结》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》

希望本文所述对大家java程序设计有所帮助。

推荐阅读:
  1. IOS XML与JSON解析
  2. xml与Java之间的转换示例

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java xml json

上一篇:基于xpath选择器、PyQuery、正则表达式的格式清理工具详解

下一篇:Eclipse引用XSD实现XML配置文件提示标签的方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》