java 非标准 json(无双引号,含特殊字符,空值) 的简易解析方法一二

本贴最后更新于 1711 天前,其中的信息可能已经时过境迁

怪事(json)年年有,今年何其多

{code=0000,
 	charset=UTF-8, 
 	mId=51000001, 
 	rDesc=, 
 	cy=156, 
 	sendTime=20200316061253,
 	cId=test-1, 
 	tType=01, 
 	pSt=02, 
 	oNum=TEST_1584339173825,
 	pT=00, 
 	orSeq=20031614120015152511,
 	omt=1}

方案一,处理字符串为全标准 json

public static void main(String[] args) {
	String a = "{code=0000,charset=UTF-8, mId=51000001, rDesc=, cy=156, sendTime=20200316061253,cId=test-1, tType=01, pSt=02, oNum=TEST_1584339173825,pT=00, orSeq=20031614120015152511,omt=1}";
	//方案一,处理字符串为全标准json
	String b = a.replaceAll(" ","").replaceAll("=","\":\"");

	b = b.replaceAll("\\{","{\"");
	b = b.replaceAll("}","\"}");
	b = b.replaceAll(",","\",\"");
	JSONObject data = JSON.parseObject(b);
	logger.info("b0:"+b);
	logger.info("b1:"+data.toJSONString());

}

方案一,程序输出

b0:{"code":"0000","charset":"UTF-8","mId":"51000001","rDesc":"","cy":"156","sendTime":"20200316061253","cId":"test-1","tType":"01","pSt":"02","oNum":"TEST_1584339173825","pT":"00","orSeq":"20031614120015152511","omt":"1"}
b1:{"charset":"UTF-8","code":"0000","tType":"01","oNum":"TEST_1584339173825","pT":"00","rDesc":"","mId":"51000001","orSeq":"20031614120015152511","sendTime":"20200316061253","pSt":"02","cy":"156","omt":"1","cId":"test-1"}

方案二,处理字符串为半标准 json+Gson

public static void main(String[] args) {
	//方案二,处理字符串为半标准json+Gson
	String aa = "{code=0000,charset=UTF-8, mId=51000001, rDesc=, cy=156, sendTime=20200316061253,cId=test-1, tType=01, pSt=02, oNum=TEST_1584339173825,pT=00, orSeq=20031614120015152511,omt=1}";

	String bb = aa.replaceAll("=",":").replaceAll(":,",":\"\",");
	logger.info("bb0:"+bb);
	Gson g = new Gson();
	JsonObject obj = g.fromJson(bb, JsonObject.class);
	logger.info("bb1:"+obj.toString());

}

方案二,程序输出

bb0:{code:0000,charset:UTF-8, mId:51000001, rDesc:"", cy:156, sendTime:20200316061253,cId:test-1, tType:01, pSt:02, oNum:TEST_1584339173825,pT:00, orSeq:20031614120015152511,omt:1}
bb1:{"code":"0000","charset":"UTF-8","mId":51000001,"rDesc":"","cy":156,"sendTime":20200316061253,"cId":"test-1","tType":"01","pSt":"02","oNum":"TEST_1584339173825","pT":"00","orSeq":20031614120015152511,"omt":1}
  • Java

    Java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由 Sun Microsystems 公司于 1995 年 5 月推出的。Java 技术具有卓越的通用性、高效性、平台移植性和安全性。

    3187 引用 • 8213 回帖
  • JSON

    JSON (JavaScript Object Notation)是一种轻量级的数据交换格式。易于人类阅读和编写。同时也易于机器解析和生成。

    52 引用 • 190 回帖
2 操作
cloudlang 在 2020-03-16 19:27:57 更新了该帖
cloudlang 在 2020-03-16 19:25:42 更新了该帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...
  • 233333

    huaji 这种 substring2 个大括号,split 逗号,等号。最近还见过那种中文做 key 的。。还是某某云的

    1 回复
  • cloudlang

    😂 好吧,这 json 也是某某行的