JackJsontools
背景:
springboot 基于jackjson来的,又在实际框架开发中,需要js一样配置,在java中 json工具很多,但用json 作配置,key必须用双引号 很烦人。故有下面的工具。
代码:
1 import javax.script.Invocable; 2 import javax.script.ScriptEngine; 3 import javax.script.ScriptEngineManager; 4 import javax.script.ScriptException; 5 import java.io.FileNotFoundException; 6 import java.io.FileReader; 7 import java.io.IOException; 8 import java.util.logging.Level; 9 import java.util.logging.Logger; 10 11 public class JackJsonUtils { 12 private static Logger log = Logger.getLogger(JackJsonUtils.class.getName()); 13 14 static ObjectMapper objectMapper; 15 16 /** 17 * 解析json 18 * 19 * @param content 20 * @param valueType 21 * @return 22 */ 23 public static <T> T fromJson(String content, Class<T> valueType) { 24 if (objectMapper == null) { 25 objectMapper = new ObjectMapper(); 26 } 27 try { 28 return objectMapper.readValue(content, valueType); 29 } catch (Exception e) { 30 e.printStackTrace(); 31 } 32 return null; 33 } 34 35 /** 36 * 生成json 37 * 38 * @param object 39 * @return 40 */ 41 public static String toJson(Object object) { 42 if (objectMapper == null) { 43 objectMapper = new ObjectMapper(); 44 } 45 try { 46 return objectMapper.writeValueAsString(object); 47 } catch (Exception e) { 48 e.printStackTrace(); 49 } 50 return null; 51 } 52 53 /** 54 * js对象字符串 转标准JSON字符串 55 * 在java配置中,不想太多的Bean类,可以用js对象写配置文件,然后转成 56 * 标准的JSON格式,再转换成标准的Map实例,用Map工具对其中的值进行读写 57 * @param jsObjectStr js脚本中的对象 58 * @return 59 */ 60 public static String getStdJsonStr(String jsObjectStr){ 61 ScriptEngineManager manager = new ScriptEngineManager(); 62 ScriptEngine engine = manager.getEngineByName("javascript"); 63 try{ 64 Object obj=engine.eval("JSON.stringify(" +jsObjectStr+")"); 65 66 return obj.toString(); 67 }catch(Exception e){ 68 return null; 69 } 70 } 71 72 /** 73 * 从js文件中的对象转标准JSON 74 * @param fileName js脚本中,在包类.根为 resources 75 * @return 76 */ 77 public static String getStdJsonStr(String fileName,String obj){ 78 ScriptEngineManager manager = new ScriptEngineManager(); 79 ScriptEngine engine = manager.getEngineByName("javascript"); 80 try{ 81 ClassLoader classLoader=Thread.currentThread().getContextClassLoader(); 82 FileReader fileReader = new FileReader(classLoader.getResource(fileName).getPath() ); 83 Object obj1 = engine.eval(fileReader); 84 obj1=engine.eval("JSON.stringify(" +obj+")"); 85 return obj1.toString(); 86 }catch(ScriptException | FileNotFoundException e){ 87 e.printStackTrace(); 88 return null; 89 } 90 } 91 }
测试与使用
aa.js
var man={ no:1, name:"wang" }
test
//展示通过js对象转标准JSON字符串,再转成Map实例 String str1=JackJsonUtils.getStdJsonStr("{no:1,name:'张三'}"); Map<String,Object> map1 =JackJsonUtils.fromJson(str1,Map.class ); str1=JackJsonUtils.getStdJsonStr("aa.js","man"); map1 =JackJsonUtils.fromJson(str1,Map.class );