java格式json和js格式json互转

时间:2020-11-27 19:05:24

遇见问题:

   在开发爬虫过程中,我们会遇见提取html页面中的json数据。由于java与js的json格式不同,故需要转化。


举例:

js中json:

{
number: "188**727499",
intLoginType: "4",
areaCode: "0471",
isBusinessCustType: "N",
identifyType: "B",
userLoginType: "4",
password: "",
randomPass: "",
noCheck: "N",
isSSOLogin: "Y",
sRand: "SSOLogin"
}

java中json:

{
"number": "188**727499",
"intLoginType": "4",
"areaCode": "0471",
"isBusinessCustType": "N",
"identifyType": "B",
"userLoginType": "4",
"password": "",
"randomPass": "",
"noCheck": "N",
"isSSOLogin": "Y",
"sRand": "SSOLogin"
}

我们可以很清晰地看出差别,就是java相对js的json多了双引号。

解决办法:

js格式json互转java格式json

String json = JSON.toJSON(JSON.parse(resultJson)).toString()

使用的是fastjson

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>


java格式json互转js格式json

<script type="text/javascript">
var json=eval('('+data+')');
<script/>
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");Invocable invocable = (Invocable) engine;Object result = invocable.invokeFunction("eval", "'("+json.toString()+")'");System.out.println(result) ;