{
'from':['Apple <no_reply@email.apple.com>'],
'to':['youngqiankun@163.com'],
'flags':{
},
'subject':'收据',
'date':new Date(2017,7,10,8,11,20),
'priority':3
}
以上为响应的代码,如何把它转化为java中的json对象?
使用Gson
,fastjson
都不行...
{
'from':['Apple <no_reply@email.apple.com>'],
'to':['youngqiankun@163.com'],
'flags':{
},
'subject':'收据',
'date':new Date(2017,7,10,8,11,20),
'priority':3
}
以上为响应的代码,如何把它转化为java中的json对象?
使用Gson
,fastjson
都不行...
最后做出来了,但是没有特别满意
package com.honey.js;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.script.ScriptException;
import org.apache.commons.io.FileUtils;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import com.google.common.base.Charsets;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class JavaScriptResponse {
private static final String regex = "(new\\s+Date\\([0-9,]+\\))";
private static final String df = "yyyy-MM-dd HH:mm:ss";
public static void main(String[] args) throws IOException, ScriptException {
String resp = FileUtils.readFileToString(new File("resp.js"), Charsets.UTF_8.toString());
System.out.println(resp);
//正则部分
Pattern p = Pattern.compile(regex);
System.out.println(p.pattern());
Matcher m = p.matcher(resp);
StringBuffer sb = new StringBuffer();
while(m.find()) {
Date date = convert(m.group(1));
String str = "'" + formatDate(date)+"'";
m.appendReplacement(sb, str);
}
m.appendTail(sb);
String ret = sb.toString();
System.out.println(ret);
Gson gson = new Gson();
Map<String, Object> myMap = gson.fromJson(ret, new TypeToken<Map<String, Object>>(){}.getType());
System.out.println(myMap);
}
private static String formatDate(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat(df);
return sdf.format(date);
}
private static Date convert(String text) {
try {
Context cx = Context.enter();
Scriptable scope = cx.initStandardObjects();
Object result = cx.evaluateString(scope, text, "<cmd>", 1, null);
Date date = (Date) Context.jsToJava(result, Date.class);
return date;
} finally {
Context.exit();
}
}
}
一些maven依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mozilla/rhino -->
<dependency>
<groupId>org.mozilla</groupId>
<artifactId>rhino</artifactId>
<version>1.7.7.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.1</version>
</dependency>
10 回答11.3k 阅读
5 回答4.9k 阅读✓ 已解决
4 回答3.2k 阅读✓ 已解决
8 回答6.4k 阅读
2 回答2.8k 阅读✓ 已解决
3 回答2.4k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
响应代码的格式,本身就不是json的格式,如何转成java的json那?