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

怪事(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 技术具有卓越的通用性、高效性、平台移植性和安全性。

    2712 引用 • 7991 回帖 • 778 关注
  • JSON

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

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

赞助商 我要投放

2 回帖
请输入回帖内容 ...
  • 233333

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

    1 回复
  • cloudlang

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