point There is a JavaScript engine in the library that comes with the JVM, so use that.
[Addition] ↓ There is an improved version here. Code used when you want to process Json with only the standard library in Java (improved version) gson unnecessary https://qiita.com/oyahiroki/items/006b3511fc4136d02ad1
package script;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class JsonUtil {
public static Object get(String json, String code) {
// Get the JavaScript engine
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
String script = "var obj = " + json + ";";
try {
engine.eval(script);
{
return engine.eval("obj." + code);
}
} catch (ScriptException e) {
e.printStackTrace();
return null;
}
}
//How to use/ How to use
public static void main(String[] args) {
String json = "{'test':'this is test','test2':{'test3':'value3'}}";
{
Object value = JsonUtil.get(json, "test");
System.out.println(value);
}
{
Object value = JsonUtil.get(json, "test2.test3");
System.out.println(value);
}
}
}
Output result
this is test
value3
Recommended Posts