gson is also convenient, but I found it troublesome, such as not being able to trace multiple layers at once, so I am making such a tool. Also, there are many boring reasons that "I really want to use Gson in the XX system, but internal approval is troublesome".
You can use it like this.
public static void main(String[] args) {
String json = "{'test':'this is test','test2':{'test3':'value3'},'test4':['a','b','c']}";
{
Object value = JsonUtil.get(json, "test"); // <-
System.out.println(value); // "this is test"
}
{
Object value = JsonUtil.get(json, "test2.test3"); // <-I want to do this
System.out.println(value); // "value3"
}
{
Object[] value = JsonUtil.getAsArray(json, "test4");
System.out.println(Arrays.toString(value)); // ["a","b","c"]
System.err.println(value.getClass());
for (int n = 0; n < value.length; n++) {
System.err.println(value[n]);
}
}
}
Below is the source code. Feel free to copy or modify it before use.
package pkg;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class JsonUtil {
public static Object[] getAsArray(String json, String code) {
Object obj = get(json, code);
if (obj instanceof Object[]) {
return (Object[]) obj;
} else {
return null;
}
}
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);
{
Object obj = engine.eval("obj." + code);
if (obj instanceof Map) {
java.util.Map map = (java.util.Map) obj;
Set entrySet = map.entrySet();
Object[] arr = new Object[entrySet.size()];
int n = 0;
for (Object objValue : map.values()) {
if (objValue instanceof String) {
String sValue = (String) objValue;
arr[n] = sValue;
} else {
arr[n] = map.get(obj);
}
n++;
}
return arr;
}
return obj;
}
} catch (ScriptException e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
String json = "{'test':'this is test','test2':{'test3':'value3'},'test4':['a','b','c']}";
{
Object value = JsonUtil.get(json, "test");
System.out.println(value); // "this is test"
}
{
Object value = JsonUtil.get(json, "test2.test3");
System.out.println(value); // "value3"
}
{
Object[] value = JsonUtil.getAsArray(json, "test4");
System.out.println(Arrays.toString(value)); // ["a","b","c"]
System.err.println(value.getClass());
for (int n = 0; n < value.length; n++) {
System.err.println(value[n]);
}
}
}
}
Recommended Posts