Java読み込みJSONファイルをMapオブジェクトに変換

13768 ワード

Java読み込みJSONファイルをMapオブジェクトに変換
  • アプリケーションシーン
  • 読み出される外部JSONファイル
  • Javaコード
  • 読み出し結果
  • Gson

  • シーンの適用
  • JarパッケージまたはWarパッケージは、プロジェクトとして実行されるプロファイル
  • として外部ファイルを参照します.
  • Jsonはkey-value形式を採用し、プロファイルとして、
  • を選択するのに良いです.
  • JSONはテキスト形式のデータ交換フォーマットであり、XMLよりも軽量で、バイナリよりも読みやすく、書きやすく、調式も
  • より便利である.
  • ファイルの読み取りは、データベースの読み取りに対して、より効率的である
  • .
    読み込む外部JSONファイル
  • 内容は任意ですが、Json文法
  • に従ってください.
    {
    	"name": "  ",
    	"skill": {
    		"JavaScript": {
    			"level": "9",
    			"class": ["JQuery", "Vue", "AngularJS", "React"]
    		},
    		"NodeJS": {
    			"level": "8",
    			"class": ["Express"]
    		},
    		"Java": {
    			"level": "7",
    			"class": ["Spring", "SpringBoot", "SpringCloud"]
    		},
    		"SQL": {
    			"level": "7",
    			"class": ["MySQL", "MongoDB", "Redis"]
    		}
    	}
    }
    

    Javaコード
    /**
     * @author ZhongLi
     */
    package com.swmfizl;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.Reader;
    import java.util.Map;
    
    import com.google.gson.Gson;
    
    public class ReadJsonFile {
    	public static Map<String, Object> readJsonFile(String fileName) {
    		Gson gson = new Gson();
    		String json = "";
    		try {
    			File file = new File(fileName);
    			Reader reader = new InputStreamReader(new FileInputStream(file), "utf-8");
    			int ch = 0;
    			StringBuffer buffer = new StringBuffer();
    			while ((ch = reader.read()) != -1) {
    				buffer.append((char) ch);
    			}
    			reader.close();
    			json = buffer.toString();
    			return gson.fromJson(json, Map.class);
    		} catch (IOException e) {
    			e.printStackTrace();
    			return null;
    		}
    	}
    
    	public static void main(String[] args) {
    		// TODO          
    		System.out.println(readJsonFile("C:\\Users\\ZhongLi\\Desktop\\config.json"));
    	}
    
    }
    

    結果の読み込み
    {name=  , skill={JavaScript={level=9, class=[JQuery, Vue, AngularJS, React]}, NodeJS={level=8, class=[Express]}, Java={level=7, class=[Spring, SpringBoot, SpringCloud]}, SQL={level=7, class=[MySQL, MongoDB, Redis]}}}
    

    Gson
  • Gsonは、JavaオブジェクトとJSONデータとの間でマッピングするためのJavaクラスライブラリ
  • である
  • JSON文字列をJavaオブジェクトに変換するか、逆に