4
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Java で Json を標準ライブラリだけで処理したいときに使うコード

Last updated at Posted at 2018-07-05

ポイント
JVM標準で使えるライブラリにJavaScriptのエンジンがありますので、それを利用します。

【追記1】
↓こちらに改良版があります。
Java で Json を標準ライブラリだけで処理したいときに使うコード(改良版)gson 不要
https://qiita.com/oyahiroki/items/006b3511fc4136d02ad1

【追記2】
Java 17では Script Engine の除外にともない、この技は利用できません.
まあこの記事が必要な方はもうしばらく Java 8 だと思いますが。。

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
	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);
		}

	}

}


出力結果

this is test
value3
4
15
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?