Android中使用GSON包解析JSON数据(复杂JSON)

时间:2022-02-21 10:22:23

      之前讨论过用GSON解析较为简单的JSON,这次稍微增加一点难度。把JSON弄的复杂一点,使JSON变为2层嵌套,并增加了一些其他元素。代码中把language.json放到assets文件夹下,把GSON.jar放到libs文件夹下。如果用的是Android Studio,需要右键GSON,jar,选择Add As Lirbary,否则AS不能识别。Eclipse中不需要这个步骤。具体解析以下三种类型的JSON:

 "first": "mobile",
 "second": "pc",

 "app": {
        "google": "android",
        "apple": "iOS",
        "microsoft": "wp"
    }

 "language": [
        {
            "id": 1,
            "name": "Java",
            "ide": "Eclipse"
        },
        {
            "id": 2,
            "name": "C++",
            "ide": "Visual Studio"
        }
    ]

languages.json的JSON代码总体如下:

{
    "first": "mobile",
    "second": "pc",
    "app": {
        "google": "android",
        "apple": "iOS",
        "microsoft": "wp"
    },
    "language": [
        {
            "id": 1,
            "name": "Java",
            "ide": "Eclipse"
        },
        {
            "id": 2,
            "name": "C++",
            "ide": "Visual Studio"
        }
    ]
}

        对于三种不同的类型,分别建立3个类,用于映射JSON中的属性。

Root.java如下:

public class Root {

    private String first;
    private String second;

    public void setFirst(String first) {
        this.first = first;
    }

    public void setSecond(String second) {
        this.second = second;
    }

    public String getFirst() {

        return first;
    }

    public String getSecond() {
        return second;
    }
}

App.java如下:

public class App {

    private String google;
    private String apple;
    private String microsoft;

    public void setGoogle(String google) {
        this.google = google;
    }

    public void setApple(String apple) {
        this.apple = apple;
    }

    public void setMicrosoft(String microsoft) {
        this.microsoft = microsoft;
    }

    public String getGoogle() {

        return google;
    }

    public String getApple() {
        return apple;
    }

    public String getMicrosoft() {
        return microsoft;
    }
}

Language.java如下:

public class Language {

    private String id;
    private String name;
    private String ide;

    public void setId(String id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setIde(String ide) {
        this.ide = ide;
    }

    public String getId() {

        return id;
    }

    public String getName() {
        return name;
    }

    public String getIde() {
        return ide;
    }
}

       以上的三个类体现了GSON解析的面向对象的思想。使用类中的属性来对应JSON中的键,使用类中的get方法来获取JSON中的值。解析的过程如下,直接上代码:

public class MainActivity extends Activity {

    private TextView text;
    private String jsonString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = (TextView) findViewById(R.id.id_text);
        getJSONString();//从language.json中获得JSON字符串;
        parseRoot(jsonString);
        parseApp(jsonString);
        parseLanguage(jsonString);
    }

    /**
     * 从languages.json中读取JSON字符串;
     */
    public void getJSONString() {
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(getAssets().open("languages.json"), "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);//使用BufferReader读取输入流中的数据;
            String line;
            StringBuilder stringBuilder = new StringBuilder();//所有读取的json放到StringBuilder中,这里也可以使用StringBuffer,效果一样;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            jsonString = stringBuilder.toString();
            bufferedReader.close();//按相反的顺序关闭流;
            inputStreamReader.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 先解析:
     * "first": "mobile",
     * "second": "pc",
     * 也就是JSON的第一层嵌套;
     *
     * @param json
     */
    private void parseRoot(String json) {
        Gson gson = new Gson();
        Root root = gson.fromJson(json, Root.class);
        text.append(root.getFirst() + "\n");
        text.append(root.getSecond() + "\n");
    }

    /**
     * 然后解析:
     * "app": {
     * "google": "android",
     * "apple": "iOS",
     * "microsoft": "wp"
     * }
     *
     * @param json
     */
    private void parseApp(String json) {

        try {
            Gson gson = new Gson();
            JSONObject roo = new JSONObject(json);
            App app = gson.fromJson(roo.getString("app"), App.class);
            text.append(app.getGoogle() + "   " + app.getApple() + "   " + app.getMicrosoft() + "\n");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 最后解析:也就是JSON数组。
     * "language": [
     * {
     * "id": 1,
     * "name": "Java",
     * "ide": "Eclipse"
     * },
     * {
     * "id": 2,
     * "name": "C++",
     * "ide": "Visual Studio"
     * }
     * ]
     *
     * @param json
     */
    private void parseLanguage(String json) {

        try {
            Gson gson = new Gson();
            Type type = new TypeToken<ArrayList<Language>>() {
            }.getType();
            JSONObject roo = new JSONObject(json);
            ArrayList<Language> languages = gson.fromJson(roo.getString("language"), type);

            for (int i = 0; i < languages.size(); i++) {
                Language lan = languages.get(i);
                text.append(lan.getId() + "   " + lan.getName() + "   " + lan.getIde() + "\n");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


}


        程序实现的效果如下:

Android中使用GSON包解析JSON数据(复杂JSON)

至此,已经成功实现用GSON解析较为复杂的JSON。


附GSON包下载:http://pan.baidu.com/s/1ntuxTRr