Java 使用gson 解析 Json

json数据

解析JSONObject

Java 使用gson 解析 Json
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.google.gson.JsonIOException;

import java.io.FileNotFoundException;
import java.io.FileReader;

public class ReadJson {
    public static void main(String []args) {
        JsonParser parse = new JsonParser();
        try {
            JsonObject json = (JsonObject) parse.parse(new FileReader("weather.json"));
            System.out.println("resultcode:" + json.get("resultcodeu").getAsInt());
            System.out.println("reason:" + json.get("reason").getAsString());
            JsonObject result = json.get("result").getAsJsonObject();
            JsonObject today = result.get("today").getAsJsonObject();
            System.out.println("weak:" + today.get("week").getAsString());
            System.out.println("weather:" + today.get("weather").getAsString());
        } catch (JsonIOException e) {
            e.printStackTrace();
        }  catch (NullPointerException e) {
            e.printStackTrace();
        }  catch (JsonSyntaxException e){
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
Java 使用gson 解析 Json

解析JSONArray

Java 使用gson 解析 Json
import com.google.gson.JsonParser;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.google.gson.JsonIOException;

import java.io.FileNotFoundException;
import java.io.FileReader;

public class ReadJsonArray {
    public static void main(String []args) {
        JsonParser parse = new JsonParser();
        try {
            JsonObject json = (JsonObject)parse.parse(new FileReader("C:\\Users\\jihite\\IdeaProjects\\TestProject\\jsontest\\src\\main\\java\\weather.json"));
            JsonObject result = json.get("result").getAsJsonObject();
            JsonArray futureArray = result.get("future").getAsJsonArray();
            for (int i = 0; i < futureArray.size(); ++i) {
                JsonObject subObj = futureArray.get(i).getAsJsonObject();
                System.out.println("------");
                System.out.println("week:" + subObj.get("week").getAsString());
                System.out.println("weather:" + subObj.get("weather").getAsString());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (JsonIOException e) {
            e.printStackTrace();
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
    }
}
Java 使用gson 解析 Json

注意

文件路径相对路径是从工程根目录开始

Java 使用gson 解析 Json

 






本文转自jihite博客园博客,原文链接:http://www.cnblogs.com/kaituorensheng/p/6616126.html,如需转载请自行联系原作者