Code used when you want to process Json with only the standard library in Java (improved version) gson unnecessary

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

Code used when you want to process Json with only the standard library in Java (improved version) gson unnecessary
Code to use when you want to process Json with only standard library in Java
When you want to implement Java library testing in Spock with multi-module in Gradle in Android Studio 3
Comparison of version strings (Java implementation) when you want to branch the process between two versions
The first thing to do when you want to be happy with Heroku on GitHub with Eclipse in Java
When you want to dynamically replace Annotation in Java8
Use JLine when you want to handle keystrokes on the console character by character in Java
[Java] I want to perform distinct with the key in the object
[Words spelled to me when I was in the first grade ⑦] What I want you to include at least with the Visual Studio Code extension
I want to get the IP address when connecting to Wi-Fi in Java
[Java] Use cryptography in the standard library
[For beginners] When you want to say that the JVM (-D) option does not work with the java -jar command, or that the library is buggy.
Try adding text to an image in Scala using the Java standard library
Code to escape a JSON string in Java
When you want to bind InputStream in JDBI3
A note when you want Tuple in Java
When you want to use the method outside
Summary of copy and paste commands used when you want to delete the cache in iOS application development anyway
You also need to specify the host when debugging remotely with Java 9 or later
Summary of how to use the proxy set in IE when connecting with Java
How to implement UICollectionView in Swift with code only
[Java] How to encrypt with AES encryption with standard library
Source used to get the redirect source URL in Java
If you want to recreate the instance in cloud9
Differences in code when using the length system in Java
[Spring Dtata JPA] How to deal with the problem that DB change cannot be detected when you want to process API synchronously with a single thread in Spring Boot.
[Ruby + Rails] When you want to register in Mailchimp's mail list together with user registration
In Java, I want to trim multiple specified characters from only the beginning and end.
How to write in Model class when you want to save binary data in DB with PlayFramework
When you want to reflect the Master Branch information in the Current Branch you are currently working on
[Java] Change the process according to the situation with the Strategy pattern
[Java] [jackson] Corresponds to the trailing comma (trailing comma) when parsing JSON.
When you want to explicitly write OR or AND with ransack
Post back the coupon code you used to the specified endpoint
Things to be aware of when writing code in Java
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
When you want to change the MySQL password of docker-compose
A memo to start Java programming with VS Code (2020-04 version)
docker-compose.yml when you want to keep mysql running with docker
lombok.config when you want to pass @Qualifier to @RequiredArgsConstructor with lombok
[Java] I want to test standard input & standard output with JUnit
I want to simplify the conditional if-else statement in Java
[Swift] When you want to know if the number of characters in a String matches a certain number ...
Object-oriented design that can be used when you want to return a response in form format
[For super beginners] The minimum knowledge you want to keep in mind with hashes and symbols
What to do when you want to know the source position where the method is defined in binding.pry