Android使用Gson解析数据

使用Gson前需要添加依赖或者添加jar包

添加jar包:下载Gson的jar包,放在android项目的libs文件夹里,右键jar包,点击Add As Libary...

1.将json格式的字符串转换为java对象

 //将json格式的字符串转换为java对象
    private void jsonToJavaObjectByGson() {
        //获取或创建JSON数据
        String json = "{\n" +
                "    \"id\":2,\n" +
                "    \"name\":\"小虾米\",\n" +
                "    \"price\":21.9,\n" +
                "    \"imagePath\":\"http://192.168.10.165:8080/server/images/xia.jpg\"\n" +
                "}";
        //解析JSON数据
        Gson gson = new Gson();
        ShopBean shopBean = gson.fromJson(json, ShopBean.class);//shopBean为解析后的数据
        //展示数据
        tv_native_original.setText(json);
        tv_native_last.setText(shopBean.toString());

    }

2.将json格式的字符串转换为java对象的List

    //将json格式的字符串转换为java对象的List
    private void jsonToJavaListByGson() {
        //获取或创建JSON数据
        String json = "[\n" +
                "    {\n" +
                "        \"id\":1,\n" +
                "        \"name\":\"小虾米1\",\n" +
                "        \"price\":21.9,\n" +
                "        \"imagePath\":\"http://192.168.10.165:8080/server/images/xia.jpg\"\n" +
                "    },\n" +
                "    {\n" +
                "        \"id\":2,\n" +
                "        \"name\":\"小虾米2\",\n" +
                "        \"price\":22.9,\n" +
                "        \"imagePath\":\"http://192.168.10.165:8080/server/images/xia.jpg\"\n" +
                "    } \n" +
                "]";
        //解析JSON数据
        Gson gson = new Gson();
        List shops = gson.fromJson(json, new TypeToken>() {
        }.getType());
        //展示数据
        tv_native_original.setText(json);
        tv_native_last.setText(shops.toString());
    }

3.将java对象转换为json字符串

 //将java对象转换为json字符串
    private void javaToJsonObjectByGson() {
        //获取或创建java对象
        ShopBean shopBean = new ShopBean(3,"海参",89.9,"192.123.114/shen.jpg");
        //生成JSON数据
        Gson gson = new Gson();
        String json = gson.toJson(shopBean);
        //展示数据
        tv_native_original.setText(shopBean.toString());
        tv_native_last.setText(json);
    }

4.将java对象的List转换为json字符串

    //将java对象的List转换为json字符串
    private void javaToJsonArrayByGson() {
        //获取或创建java对象
        List shops = new ArrayList<>();
        ShopBean baoyu = new ShopBean(7,"鲍鱼",99.9,"192.123.114/yu.jpg");
        ShopBean haishen = new ShopBean(3,"海参",89.9,"192.123.114/shen.jpg");
        shops.add(baoyu);
        shops.add(haishen);
        //生成JSON数据
        Gson gson = new Gson();
        String json = gson.toJson(shops);
        //展示数据
        tv_native_original.setText(shops.toString());
        tv_native_last.setText(json);
    }

完整DemoGson数据解析

你可能感兴趣的:(android)