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之间的转换的更多相关文章

  1. Json与javaBean之间的转换工具类

    /**  * Json与javaBean之间的转换工具类  *  * {@code 现使用json-lib组件实现  *    需要  *     json-lib-2.4-jdk15.jar  * ...

  2. 使用JAXB来实现Java合xml之间的转换

    使用jaxb操作Java与xml之间的转换非常简单,看个例子就明白了. //javaBean-->xml @Test public void test1() { try { JAXBContex ...

  3. java与xml之间的转换(jaxb)

    使用java提供的JAXB来实现java到xml之间的转换,先创建两个持久化的类(Student和Classroom): Classroom: package com.model; public cl ...

  4. Java基础97 json插件的使用(java对象和json字符串对象之间的转换)

    1.需要用到的包 2.实例 实体类 people package com.shore.entity; /** * @author DSHORE/2019-4-19 * */ public class ...

  5. JsonConvert对象实现json与对象之间的转换

    自己下载Newtonsoft.Json文件 使用JsonConvert对象转换 1. 2.添加引用到项目中,然后导入命名空间 3.就可以使用JsonConvert对象实现Json与类型之间的转换

  6. IDEA使用GsonFormat完成JSON和JavaBean之间的转换

    原文地址:https://www.leshalv.net/posts/12625/ 前言: 之前处理接口传来的一堆数据,用jsonObject很难受,后面就用gosn来弄,配合这个工具体验很好. 转: ...

  7. JSON-lib框架,JAVA对象与JSON、XML之间的相互转换

    Json-lib可以将Java对象转成json格式的字符串,也可以将Java对象转换成xml格式的文档,同样可以将json字符串转换成Java对象或是将xml字符串转换成Java对象. 一. 准备工作 ...

  8. 做筛选遍历时遇到的json字符串、json对象、json数组 三者之间的转换问题

    这个是后台对登录用户以及筛选条件的操作 @Override public List<SdSdPer> listResults(String sidx, String sord) { try ...

  9. 关于json和字符串之间的转换

    在最近的工作中,使用到JSON进行数据的传递,特别是从前端传递到后台,前台可以直接采用ajax的data函数,按json格式传递,后台Request即可,但有的时候,需要传递多个参数,后台使用requ ...

随机推荐

  1. @ControllerAdvice+@ExceptionHandler处理架构异常捕获

    1.注解引入 1) @ControllerAdvice - 控制器增强 @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) ...

  2. BZOJ2040[2009国家集训队]拯救Protoss的故乡——模拟费用流+线段树+树链剖分

    题目描述 在星历2012年,星灵英雄Zeratul预测到他所在的Aiur行星在M天后会发生持续性暴雨灾害,尤其是他们的首都.而Zeratul作为星灵族的英雄,当然是要尽自己最大的努力帮助星灵族渡过这场 ...

  3. Git——入门操作加创建账号【三】

    创建账号 GitHub https://github.com/ 码云 https://gitee.com/ 无论是github还是码云,创建账号都是非常简单快捷的,大家可以自行选择创建下,不过建议最好 ...

  4. python深度学习库keras——安装

    TensorFlow安装keras需要在TensorFlow之上才能运行.所以这里安装TensorFlow.TensorFlow需要vs2015环境,需要wein64位环境,所以32位的小伙伴需要升级 ...

  5. Python可迭代对象中的添加和删除(add,append,pop,remove,insert)

    list: classmates = ['Michael', 'Bob', 'Tracy'] classmates.append('Adam') //添加在末尾,没有add()方法 classmate ...

  6. 【XSY1098】第k小 可持久化trie

    题目描述 给你一个长度为\(n\)数列\(a\),有\(m\)次操作: \(1~x\):把所有数异或\(x\) \(2~x\):把所有数与\(x\) \(3~x\):把所有数或\(x\) \(4~l~ ...

  7. Codeforces Round #545 (Div. 2) D

    链接:http://codeforces.com/contest/1138/problem/D 啊啊啊啊啊啊,自闭啊,比赛的时候判断条件 if(s1[i-1]=='0') aa++;写成了 if(s1 ...

  8. 【模板】可持久化文艺平衡树-可持久化treap

    题目链接 题意 对于各个以往的历史版本实现以下操作: 在第 p 个数后插入数 x . 删除第 p 个数. 翻转区间 [l,r],例如原序列是 \(\{5,4,3,2,1\}\),翻转区间 [2,4] ...

  9. Configure new Nagios clients

    安装rpm -Uvh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpmrpm -Uvh http:// ...

  10. Atcoder 乱做

    最近感觉自己思维僵化,啥都不会做了-- ARC103 F Distance Sums 题意 给定第 \(i\) 个点到所有点的距离和 \(D_i\) ,要求构造一棵合法的树.满足第 \(i\) 个点到 ...