JSON与XML之间的转换
public class JsonTest {
private final Logger cLogger = Logger.getLogger(getClass()); /**
* XML转JSON
* 需import org.json.JSONObject; pom加依赖
*
*/
@Test
public void xmlToJson() { String comId="123456";
JSONObject xmlJSONObj = org.json.XML.toJSONObject("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" +
"\t<PackageList>\n" +
"\t\t<Package>\n" +
"\t\t\t<Header>\n" +
"\t\t\t\t<Version>3.0.0</Version>\n" +
"\t\t\t\t<RequestType>03</RequestType>\n" +
"\t\t\t\t<UUID>14336376457645768578</UUID>\n" +
"\t\t\t\t<ComId>123456</ComId>\n" +
"\t\t\t\t<SendTime>2014-04-22 18:00:00</SendTime>\n" +
"\t\t\t\t<FromSerial>1234567890</FromSerial>\n" +
"\t\t\t\t<ProductCode>2222222</ProductCode>\n" +
"\t\t\t</Header>\n" +
"\t\t\t<Callback>\n" +
"\t\t\t\t<OrderId>2222222</OrderId>\n" +
"\t\t\t\t<PolicyNo>2222222666</PolicyNo>\n" +
"\t\t\t\t<RefundNo>2222222666</RefundNo>\n" +
"\t\t\t\t<RespondPrice>100</RespondPrice>\n" +
"\t\t\t\t<RealRefundPrice>100</RealRefundPrice>\n" +
"\t\t\t\t<HandingFee>10</HandingFee>\n" +
"\t\t\t\t<RefundTime>2014-04-22 18:00:00</RefundTime>\n" +
"\t\t\t\t<AuditTime>2014-04-22 18:00:00</AuditTime>\n" +
"\t\t\t\t<RefundChannel>保险公司</RefundChannel>\n" +
"\t\t\t\t<RefundStatus>1</RefundStatus>\n" +
"\t\t\t\t<RefundReslut>通过</RefundReslut>\n" +
"\t\t\t\t<BankCardNo>32445646458757766775</BankCardNo>\n" +
"\t\t\t\t<RefundUser>测试</RefundUser>\n" +
"\t\t\t\t<RefundTradeNo>12355464567768686786</RefundTradeNo>\n" +
"\t\t\t\t<RefundPremium>11</RefundPremium>\n" +
"\t\t\t\t<RefundType>1</RefundType>\n" +
"\t\t\t</Callback>\n" +
"\t\t</Package>\n" +
"\t</PackageList>");
cLogger.info("XML转换后的字符串JSON为:"+xmlJSONObj.toString());
cLogger.info("XML转换后的格式化JSON为:"+formatJson(xmlJSONObj.toString())); } /**
* JSON转XML
* 需import org.json.JSONObject;
* <dependency>
* <groupId>org.json</groupId>
* <artifactId>json</artifactId>
* <version>20180813</version>
* </dependency>
*
*
*
*/
@Test
public void jsonToXml() {
String json="{\n" +
" \"PackageList\": {\n" +
" \"Package\": {\n" +
" \"Header\": {\n" +
" \"Version\": \"3.0.0\",\n" +
" \"RequestType\": \"03\",\n" +
" \"UUID\": \"14336376457645768578\",\n" +
" \"ComId\": \"123456\",\n" +
" \"SendTime\": \"2014-04-22 18:00:00\",\n" +
" \"FromSerial\": \"1234567890\",\n" +
" \"ProductCode\": \"2222222\"\n" +
" },\n" +
" \"Callback\": {\n" +
" \"OrderId\": \"2222222\",\n" +
" \"PolicyNo\": \"2222222666\",\n" +
" \"RefundNo\": \"2222222666\",\n" +
" \"RespondPrice\": \"100\",\n" +
" \"RealRefundPrice\": \"100\",\n" +
" \"HandingFee\": \"10\",\n" +
" \"RefundTime\": \"2014-04-22 18:00:00\",\n" +
" \"AuditTime\": \"2014-04-22 18:00:00\",\n" +
" \"RefundChannel\": \"保险公司\",\n" +
" \"RefundStatus\": \"1\",\n" +
" \"RefundReslut\": \"通过\",\n" +
" \"BankCardNo\": \"32445646458757766775\",\n" +
" \"RefundUser\": \"测试\",\n" +
" \"RefundTradeNo\": \"12355464567768686786\",\n" +
" \"RefundPremium\": \"11\",\n" +
" \"RefundType\": \"1\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
JSONObject jsonObj = new JSONObject(json);
cLogger.info("JSON转换后的字符串XML为:"+XML.toString(jsonObj));
cLogger.info("JSON转换后的格式化XML为:"+forMateOutData(XML.toString(jsonObj))); } /**
* 获取JSON数据
* 需import com.alibaba.fastjson.JSONObject;
*/
@Test
public void getJsonText(){
String params="{\n" +
" \"PackageList\": {\n" +
" \"Package\": {\n" +
" \"Header\": {\n" +
" \"Version\": \"3.0.0\",\n" +
" \"RequestType\": \"03\",\n" +
" \"UUID\": \"14336376457645768578\",\n" +
" \"ComId\": \"123456\",\n" +
" \"SendTime\": \"2014-04-22 18:00:00\",\n" +
" \"FromSerial\": \"1234567890\",\n" +
" \"ProductCode\": \"2222222\"\n" +
" },\n" +
" \"Callback\": {\n" +
" \"OrderId\": \"2222222\",\n" +
" \"PolicyNo\": \"2222222666\",\n" +
" \"RefundNo\": \"2222222666\",\n" +
" \"RespondPrice\": \"100\",\n" +
" \"RealRefundPrice\": \"100\",\n" +
" \"HandingFee\": \"10\",\n" +
" \"RefundTime\": \"2014-04-22 18:00:00\",\n" +
" \"AuditTime\": \"2014-04-22 18:00:00\",\n" +
" \"RefundChannel\": \"保险公司\",\n" +
" \"RefundStatus\": \"1\",\n" +
" \"RefundReslut\": \"通过\",\n" +
" \"BankCardNo\": \"32445646458757766775\",\n" +
" \"RefundUser\": \"测试\",\n" +
" \"RefundTradeNo\": \"12355464567768686786\",\n" +
" \"RefundPremium\": \"11\",\n" +
" \"RefundType\": \"1\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
com.alibaba.fastjson.JSONObject jsonObject =com.alibaba.fastjson.JSONObject.parseObject(params);
com.alibaba.fastjson.JSONObject aPackageList=com.alibaba.fastjson.JSONObject.parseObject(jsonObject.get("PackageList").toString());
com.alibaba.fastjson.JSONObject aPackage=com.alibaba.fastjson.JSONObject.parseObject(aPackageList.get("Package").toString());
com.alibaba.fastjson.JSONObject aHeader=com.alibaba.fastjson.JSONObject.parseObject(aPackage.get("Header").toString());
com.alibaba.fastjson.JSONObject aCallback=com.alibaba.fastjson.JSONObject.parseObject(aPackage.get("Callback").toString());
cLogger.info(aHeader.get("Version").toString());
cLogger.info(aCallback.get("RefundChannel").toString());
cLogger.info(aCallback.get("RefundTime").toString());
} /**
* 拼接JSON字符串
*/
@Test
public void appendStringJson(){
StringBuilder sb = new StringBuilder();
String conId="123456";
sb.append("{");
sb.append("\"PackageList\":").append("{");
sb.append("\"Package\":").append("{");
sb.append("\"Header\":").append("{");
sb.append("\"ComId\":").append("\""+conId+"\"");
sb.append(",\"FromSerial\":").append("\"1234567890\"");
sb.append(",\"ProductCode\":").append("\"2222222\"");
sb.append(",\"SendTime\":").append("\"2014-04-22 18:00:00\"");
sb.append(",\"UUID\":").append("\"14336376457645768578\"");
sb.append(",\"Version\":").append("\"3.0.0\"");
sb.append(",\"RequestType\":").append("\"03\"");
sb.append("}");
sb.append(",\"Callback\":").append("{");
sb.append("\"RefundTradeNo\":").append("\"12355464567768686786\"");
sb.append(",\"RefundTime\":").append("\"2014-04-22 18:00:00\"");
sb.append(",\"RefundStatus\":").append("\"1\"");
sb.append(",\"OrderId\":").append("\"2222222\"");
sb.append(",\"PolicyNo\":").append("\"2222222666\"");
sb.append(",\"RefundReslut\":").append("\"通过\"");
sb.append(",\"HandingFee\":").append("\"10\"");
sb.append(",\"RefundUser\":").append("\"测试\"");
sb.append(",\"BankCardNo\":").append("\"32445646458757766775\"");
sb.append(",\"RefundNo\":").append("\"2222222666\"");
sb.append(",\"AuditTime\":").append("\"2014-04-22 18:00:00\"");
sb.append(",\"RefundChannel\":").append("\"保险公司\"");
sb.append(",\"RefundPremium\":").append("\"11\"");
sb.append(",\"RealRefundPrice\":").append("\"100\"");
sb.append(",\"RespondPrice\":").append("\"100\"");
sb.append(",\"RefundType\":").append("\"1\"");
sb.append("}");
sb.append("}");
sb.append("}");
sb.append("}");
cLogger.info(sb.toString());
cLogger.info(formatJson(sb.toString())); } /**
* 格式化输出JSON报文
*
* @param jsonStr
* @return
* @author lcb
*/
public static String formatJson(String jsonStr) {
if (null == jsonStr || "".equals(jsonStr))
return "";
StringBuilder sb = new StringBuilder();
char last = '\0';
char current = '\0';
int indent = 0;
boolean isInQuotationMarks = false;
for (int i = 0; i < jsonStr.length(); i++) {
last = current;
current = jsonStr.charAt(i);
switch (current) {
case '"':
if (last != '\\'){
isInQuotationMarks = !isInQuotationMarks;
}
sb.append(current);
break;
case '{':
case '[':
sb.append(current);
if (!isInQuotationMarks) {
sb.append('\n');
indent++;
addIndentBlank(sb, indent);
}
break;
case '}':
case ']':
if (!isInQuotationMarks) {
sb.append('\n');
indent--;
addIndentBlank(sb, indent);
}
sb.append(current);
break;
case ',':
sb.append(current);
if (last != '\\' && !isInQuotationMarks) {
sb.append('\n');
addIndentBlank(sb, indent);
}
break;
default:
sb.append(current);
}
} return sb.toString();
} /**
* 添加space
*
* @param sb
* @param indent
* @author lcb
*/
private static void addIndentBlank(StringBuilder sb, int indent) {
for (int i = 0; i < indent; i++) {
sb.append('\t');
}
} /**
* 格式话输出XML报文.
*
* @param outXml
* @return
*/
private String forMateOutData(String outXml) {
Pattern p = Pattern.compile("\r|\n");
Matcher m = p.matcher(outXml);
outXml = m.replaceAll("");
Format format = Format.getPrettyFormat();
format.setEncoding("UTF-8");
XMLOutputter outputter = new XMLOutputter();
outputter.setFormat(format);
return outputter.outputString(JdomUtil.build(outXml.trim()));
}
}
JSON与XML之间的转换的更多相关文章
- Json与javaBean之间的转换工具类
/** * Json与javaBean之间的转换工具类 * * {@code 现使用json-lib组件实现 * 需要 * json-lib-2.4-jdk15.jar * ...
- 使用JAXB来实现Java合xml之间的转换
使用jaxb操作Java与xml之间的转换非常简单,看个例子就明白了. //javaBean-->xml @Test public void test1() { try { JAXBContex ...
- java与xml之间的转换(jaxb)
使用java提供的JAXB来实现java到xml之间的转换,先创建两个持久化的类(Student和Classroom): Classroom: package com.model; public cl ...
- Java基础97 json插件的使用(java对象和json字符串对象之间的转换)
1.需要用到的包 2.实例 实体类 people package com.shore.entity; /** * @author DSHORE/2019-4-19 * */ public class ...
- JsonConvert对象实现json与对象之间的转换
自己下载Newtonsoft.Json文件 使用JsonConvert对象转换 1. 2.添加引用到项目中,然后导入命名空间 3.就可以使用JsonConvert对象实现Json与类型之间的转换
- IDEA使用GsonFormat完成JSON和JavaBean之间的转换
原文地址:https://www.leshalv.net/posts/12625/ 前言: 之前处理接口传来的一堆数据,用jsonObject很难受,后面就用gosn来弄,配合这个工具体验很好. 转: ...
- JSON-lib框架,JAVA对象与JSON、XML之间的相互转换
Json-lib可以将Java对象转成json格式的字符串,也可以将Java对象转换成xml格式的文档,同样可以将json字符串转换成Java对象或是将xml字符串转换成Java对象. 一. 准备工作 ...
- 做筛选遍历时遇到的json字符串、json对象、json数组 三者之间的转换问题
这个是后台对登录用户以及筛选条件的操作 @Override public List<SdSdPer> listResults(String sidx, String sord) { try ...
- 关于json和字符串之间的转换
在最近的工作中,使用到JSON进行数据的传递,特别是从前端传递到后台,前台可以直接采用ajax的data函数,按json格式传递,后台Request即可,但有的时候,需要传递多个参数,后台使用requ ...
随机推荐
- 实现中英文混合string的逆向输出
#include <iostream> using namespace std; // 输入一个字符串(包括英文和中文),将其反序输出, 如: // hello 今天真热 ---> ...
- HDU 1556-Color the ball-树状数组
树状数组的成段更新. 首先要明白,insert函数的意思是更新某一点值,query函数的意思是从起点到某一点的和. 更新[a,b]段时,在a点插入一个1,在b+1点插入一个-1.这时,query(a) ...
- [USACO07JAN]Cow School
题目链接:[USACO07JAN]Cow School 一开始还以为是一道分数规划,后来发现自己看错题了, 然后成功入坑 题目是要求先按照$t_i/p_i$从小到大排序,然后删除前$d$个后求出剩下的 ...
- 【luogu3733】【HAOI2017】 八纵八横 (线段树分治+线性基)
Descroption 原题链接 给你一个\(n\)个点的图,有重边有自环保证连通,最开始有\(m\)条固定的边,要求你支持加边删边改边(均不涉及最初的\(m\)条边),每一次操作都求出图中经过\(1 ...
- Coding and Paper Letter(五十八)
资源整理. 1 Coding: 1.支持TMS.WMTS标准瓦片下载,支持百度地图瓦片.高德地图瓦片.腾讯地图瓦片.天地图.ArcServer Rest瓦片.ArcServer本地缓存切片.geose ...
- Leetcode 209.长度最小的子数组 By Python
给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组.如果不存在符合条件的连续子数组,返回 0. 示例: 输入: s = 7, nums = [2, ...
- 【HDU1846】Brave Game(博弈论)
题面 HDU 题解 \(Bash\ Game\)模板题 #include<iostream> using namespace std; int T,n,m; int main() { io ...
- 「SCOI2016」围棋 解题报告
「SCOI2016」围棋 打CF后困不拉基的,搞了一上午... 考虑直接状压棋子,然后发现会t 考虑我们需要上一行的状态本质上是某个位置为末尾是否可以匹配第一行的串 于是状态可以\(2^m\)压住了, ...
- layui laydate is not defined
记得引入的js文件要放到layui.js前面才会生效
- 关于windows下NODE_ENV=test无效的情况解决办法
redux的单元测试命令为 NODE_ENV=test mocha --recursive --compilers js:babel-core/register --require ./test/se ...