Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

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

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

【追記】
↓こちらに改良版があります。
Java で Json を標準ライブラリだけで処理したいときに使うコード(改良版)gson 不要
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
    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
oyahiroki
Hiroki Oya <oyahiroki> 自然言語処理技術者 NLP Engineer (2001-2018) IBMで自然言語処理ソリューションの開発 (IBM Watson) (2018-現在) 日産自動車で自然言語処理ソリューションの開発 --- #NLP4J #自然言語処理
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away