JavaでJSONを解析する方法?


この記事では、JavaでJSONを解析する方法について説明します.JSON Java、GSON、JSONのようなJSONライブラリを使います
JSONはJavaScriptのオブジェクト表記を表します.データを格納して、輸送することは、使いやすくて、開いている標準的なファイル形式を軽くします.
としてjson.org ,

It is easy for humans to read and write. It is easy for machines to parse and generate.


JSONの例
{
  "name": "coderolls",
  "type": "blog",
  "address": {
    "street": "1600 Pennsylvania Avenue NW",
    "city": "Washington",
    "state": "DC"
  },
  "employees": [
    {
      "firstName": "John",
      "lastName": "Doe"
    },
    {
      "firstName": "Anna",
      "lastName": "Smith"
    },
    {
      "firstName": "Peter",
      "lastName": "Jones"
    }
  ]
}
上記のJSONではname がキーでありcoderolls それは価値ですか.For address キー、値はキーと値を含む別のJSONオブジェクトです.
For employees キー、それはJSONオブジェクトの配列です.
今日、Javaで3つのJSONライブラリを見てJSON文字列を解析します.以下に列挙します.
  • ジャンソン
  • ギャルソン
  • シンプルソン
  • JavaでJSONを解析するために、すべての3つのライブラリの例を示します.

    JavaでJOSNを解析する方法
    JSON JavaはJavaのための最もシンプルなJSONライブラリの一つです.
    ここでは、我々はJSONObject JSON Javaライブラリのクラス.JSONObject has a constructor which accepts string . 私たちは、JSONストリングを解析するために、ths建設者を使用しています.
    public JSONObject(String source) throws JSONException
    
    Construct a JSONObject from a source JSON text string. This is the most commonly used JSONObject constructor.
    
    Parameters:
    
    source  - A string beginning with  `{` (left brace)  and ending with  `}`  (right brace).
    
    Throws:
    
    JSONException  - If there is a syntax error in the source string or a duplicated key.
    
    参照することができますJSON-java Docs .
    マベン
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20201115</version>
    </dependency>
    
    グレード
    compile group: 'org.json', name: 'json', version: '20201115'
    
    例:
    package com.coderolls.JSONExample;
    
    import org.json.JSONArray;
    import org.json.JSONObject;
    
    /**
     * A program to parse JSON strin in Java using JSON-Java
     * @author Gaurav Kukade at coderolls.com
     */
    
    public class ParseJSONUsingJSONJava {
    
        public static void main(String[] args) {
    
            String jsonString = "{"
                    + "  \"name\": \"coderolls\","
                    + "  \"type\": \"blog\","
                    + "  \"address\": {"
                    + "    \"street\": \"1600 Pennsylvania Avenue NW\","
                    + "    \"city\": \"Washington\","
                    + "    \"state\": \"DC\""
                    + "  },"
                    + "  \"employees\": ["
                    + "    {"
                    + "      \"firstName\": \"John\","
                    + "      \"lastName\": \"Doe\""
                    + "    },"
                    + "    {"
                    + "      \"firstName\": \"Anna\","
                    + "      \"lastName\": \"Smith\""
                    + "    },"
                    + "    {"
                    + "      \"firstName\": \"Peter\","
                    + "      \"lastName\": \"Jones\""
                    + "    }"
                    + "  ]"
                    + "}";
    
            System.out.println("Parsing the json string in java using JSON-Java......\n");
    
            //add jsonString to the constructor
            JSONObject coderollsJSONObject = new JSONObject(jsonString);
    
            //now we can access the values 
            String name = coderollsJSONObject.getString("name");
            System.out.println("Name: "+name+"\n");
    
            //we can get the JSON object present as value of any key in the parent JSON
            JSONObject addressJSONObject = coderollsJSONObject.getJSONObject("address");
    
            //access the values of the addressJSONObject 
            String street = addressJSONObject.getString("street");
            System.out.println("Street: "+street+"\n");
    
    
            //we can get the json array present as value of any key in the parent JSON
            JSONArray employeesJSONArray = coderollsJSONObject.getJSONArray("employees");
            System.out.println("Printing the employess json array: \n"+employeesJSONArray.toString()+"\n");
    
            //we can get individual json object at an index from the employeesJSONArray
            JSONObject employeeJSONObject = employeesJSONArray.getJSONObject(0);
            String firstName = employeeJSONObject.getString("firstName");
            System.out.println("First Name of the employee at index 0: "+firstName);
        }
    }
    
    コードを得るParseJSONUsingJSON.Java
    出力:
    Parsing the json string in java using JSON-Java......
    
    Name: coderolls
    
    Street: 1600 Pennsylvania Avenue NW
    
    Printing the employess json array: 
    [{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]
    
    First Name of the employee at index 0: John
    

    JavaでJOSNを解析する方法
    GSONは、Javaで開発されたJavaオブジェクトをシリアル化し、Javaで開発したJavaライブラリです.
    JSON文字列を等価Javaオブジェクトに変換するために使用できます.
    ここでは、我々はJsonObject GSONライブラリのクラス.
    あなたはdocs of JsonObject .
    マベン
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.6</version>
    </dependency>
    
    グレード
    compile group: 'com.google.code.gson', name: 'gson', version: '2.8.6'
    
    例:
    package com.coderolls.JSONExample;
    
    import com.google.gson.Gson;
    import com.google.gson.JsonArray;
    import com.google.gson.JsonObject;
    
    /**
     * A program to parse JSON strin in Java using Gson
     * @author Gaurav Kukade at coderolls.com
     */
    
    public class ParseJSONUsingGSON {
    
        public static void main(String[] args) {
    
            //take json as string
            String jsonString = "{"
                    + "  \"name\": \"coderolls\","
                    + "  \"type\": \"blog\","
                    + "  \"address\": {"
                    + "    \"street\": \"1600 Pennsylvania Avenue NW\","
                    + "    \"city\": \"Washington\","
                    + "    \"state\": \"DC\""
                    + "  },"
                    + "  \"employees\": ["
                    + "    {"
                    + "      \"firstName\": \"John\","
                    + "      \"lastName\": \"Doe\""
                    + "    },"
                    + "    {"
                    + "      \"firstName\": \"Anna\","
                    + "      \"lastName\": \"Smith\""
                    + "    },"
                    + "    {"
                    + "      \"firstName\": \"Peter\","
                    + "      \"lastName\": \"Jones\""
                    + "    }"
                    + "  ]"
                    + "}";
            System.out.println("Parsing the json string in java using Gson......\n");
    
            Gson gson = new Gson();
    
            //get json object from the json string
            JsonObject coderollsJsonObject = gson.fromJson(jsonString, JsonObject.class);
    
            //now we can access the values 
            String name = coderollsJsonObject.get("name").getAsString();
            System.out.println("Name: "+name+"\n");
    
            //we can get the JSON object present as value of any key in the parent JSON
            JsonObject addressJsonObject = coderollsJsonObject.get("address").getAsJsonObject();
    
            //access the values of the addressJSONObject 
            String street = addressJsonObject.get("street").getAsString();
            System.out.println("Street: "+street+"\n");
    
    
            //we can get the json array present as value of any key in the parent JSON
            JsonArray employeesJsonArray = coderollsJsonObject.get("employees").getAsJsonArray();
            System.out.println("Printing the employess json array: \n"+employeesJsonArray.toString()+"\n");
    
            //we can get individual json object at an index from the employeesJSONArray
            JsonObject employeeJsonObject = employeesJsonArray.get(0).getAsJsonObject();
            String firstName = employeeJsonObject.get("firstName").getAsString();
            System.out.println("First Name of the employee at index 0: "+firstName);
        }
    }
    
    コードを得るParseJSONUsingGSON.java
    出力:
    Parsing the json string in java using Gson......
    
    Name: coderolls
    
    Street: 1600 Pennsylvania Avenue NW
    
    Printing the employess json array: 
    [{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]
    
    First Name of the employee at index 0: John
    

    JSONシンプルを使用してJavaでJOSNを解析する方法
    JSONシンプルなJSONのJavaツールキットです.JSONを使用できます.JSONテキストをエンコードまたはデコードするのに簡単です.
    マベン
    <dependency>
        <groupId>com.googlecode.json-simple</groupId>
        <artifactId>json-simple</artifactId>
        <version>1.1.1</version>
    </dependency>
    
    グレード
    compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
    
    あなたはjson-simple project page.java .
    例:
    package com.coderolls.JSONExample;
    
    import org.json.simple.JSONArray;
    import org.json.simple.JSONObject;
    import org.json.simple.parser.JSONParser;
    import org.json.simple.parser.ParseException;
    
    /**
     * A program to parse JSON strin in Java using json-simple
     * @author Gaurav Kukade at coderolls.com
     */
    
    public class ParseJSONUsingJsonSimple {
    
        public static void main(String[] args) {
            //take json as string
            String jsonString = "{"
                            + "  \"name\": \"coderolls\","
                            + "  \"type\": \"blog\","
                            + "  \"address\": {"
                            + "    \"street\": \"1600 Pennsylvania Avenue NW\","
                            + "    \"city\": \"Washington\","
                            + "    \"state\": \"DC\""
                            + "  },"
                            + "  \"employees\": ["
                            + "    {"
                            + "      \"firstName\": \"John\","
                            + "      \"lastName\": \"Doe\""
                            + "    },"
                            + "    {"
                            + "      \"firstName\": \"Anna\","
                            + "      \"lastName\": \"Smith\""
                            + "    },"
                            + "    {"
                            + "      \"firstName\": \"Peter\","
                            + "      \"lastName\": \"Jones\""
                            + "    }"
                            + "  ]"
                            + "}";
    
            System.out.println("Parsing the json string in java using json-simple......\n");
    
            JSONParser parser = new JSONParser();
            JSONObject coderollsJSONObject = new JSONObject();
            try {
                coderollsJSONObject = (JSONObject) parser.parse(jsonString);
            } catch (ParseException e) {
                e.printStackTrace();
            }
    
            //now we can access the values 
            String name = (String) coderollsJSONObject.get("name");
            System.out.println("Name: "+name+"\n");
    
            //we can get the JSON object present as value of any key in the parent JSON
            JSONObject addressJSONObject = (JSONObject) coderollsJSONObject.get("address");
    
            //access the values of the addressJSONObject 
            String street = (String) addressJSONObject.get("street");
            System.out.println("Street: "+street+"\n");
    
    
            //we can get the json array present as value of any key in the parent JSON
            JSONArray employeesJSONArray = (JSONArray) coderollsJSONObject.get("employees");
            System.out.println("Printing the employess json array: \n"+employeesJSONArray.toString()+"\n");
    
            //we can get individual json object at an index from the employeesJSONArray
            JSONObject employeeJSONObject = (JSONObject) employeesJSONArray.get(0);
            String firstName = (String) employeeJSONObject.get("firstName");
            System.out.println("First Name of the employee at index 0: "+firstName);
        }
    }
    
    コードを得るParseJSONUsingJsonSimple.java
    出力:
    Parsing the json string in java using json-simple......
    
    Name: coderolls
    
    Street: 1600 Pennsylvania Avenue NW
    
    Printing the employess json array: 
    [{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]
    
    First Name of the employee at index 0: John
    

    結論
    すべての3つのライブラリでJSON文字列からJSONオブジェクトを作成できますが、JSON Javaは使いやすいです.
    このブログ記事はすでに公開されています.https://coderolls.com/parse-json-in-java/
    あなたはより多くのビデオチュートリアルを見つけるために私の訪問することができます.
    あなたは私をサポートすることができますgiving a cup of Coffee ☕

    関連記事
  • 8 Basic GIT Commands Every Newbie Developer Must Know
  • How To Reverse A String In Java (5 ways)
  • How To Create UUID in Java?
  • Learn About Java String Pool And intern() Method
  • How Do I Compare Strings In Java
  • Compare Two Strings Lexicographically In Java
  • Difference Between StringBuffer and StringBuilder class