Java——解析Json数据

从api接口获取数据是非常常见的开发场景。

获取的数据最常见的格式就是json数据,接下来我们学习一下json的解析方式。

1.Json数据格式

1-1 Json对象

//JsonObject.json
{
    "name": "瓦曙凤蝶",
    ": "Atrophaneura varuna",
    ": "凤蝶科",
    ": 2
}

1-2 Json数组

//JsonArray.json
{
    "data": [
    {
        "name": "曙凤蝶",
        "latinName": "Atrophaneura horishana",
        "type": "凤蝶科",
        "id": 1
    },
    {
        "name": "瓦曙凤蝶",
        "latinName": "Atrophaneura varuna",
        "type": "凤蝶科",
        "id": 2
    }]
}

1-3 复杂Json

//JsonComposite.json
{
    "code": 0,
    "message": "查询成功",
    "data": [
    {
        "name": "曙凤蝶",
        "latinName": "Atrophaneura horishana",
        "type": "凤蝶科",
        "id": 1typ
    },
    {
        "name": "瓦曙凤蝶",
        "latinName": "Atrophaneura varuna",
        "type": "凤蝶科",
        "id": 2
    }]
}

2.Json的解析

本文中采用了Gson包进行解析

Java项目中使用前需进行导包

Android项目中可添加依赖或导包

Gson包下载

注意

创建.json文件时可先创建txt文件,放入Json数据后另存为时需在最底部设置文件编码为UTF-8,否则读取的中文会变为乱码。

2-1使用JsonParser解析

· 解析JsonObject

public static void parseJsonObject(String filePath) throws FileNotFoundException{

        FileReader jsonReader = new FileReader(filePath);

        JsonParser parser = new JsonParser(); // 创建JSON解析器

        JsonObject jsonObject = (JsonObject) parser.parse(jsonReader);// 创建JsonObject对象

        System.out.println("---------------");

        //根据元素名获取其值

        System.out.println("name="+jsonObject.get("name").getAsString());

        System.out.println("latinName="+jsonObject.get("latinName").getAsString());

        System.out.println("type="+jsonObject.get("type").getAsString());

        System.out.println("id="+jsonObject.get("id").getAsString());

        System.out.println("---------------");

    }



    public static void main(String[] args) throws FileNotFoundException {

        parseJsonObject("JsonObject.json");

    }

解析结果:

· 解析JsonArray

public static void parseJsonArray(String filePath) throws FileNotFoundException {

        FileReader jsonReader = new FileReader(filePath);

        JsonParser parser = new JsonParser(); // 创建JSON解析器

        JsonObject jsonObject = (JsonObject) parser.parse(jsonReader);// 创建JsonObject对象

        JsonArray jsonArray = jsonObject.get("data").getAsJsonArray();// 得到为json的数组

        for (int i = 0; i < jsonArray.size(); i++) {

            System.out.println("---------------");

            JsonObject subObject = jsonArray.get(i).getAsJsonObject();

            System.out.println("name=" + subObject.get("name").getAsString());

            System.out.println("latinName=" + subObject.get("latinName").getAsString());

            System.out.println("type="+subObject.get("type").getAsString());

            System.out.println("id=" + subObject.get("id").getAsInt());

        }

    }



    public static void main(String[] args) throws FileNotFoundException {

        parseJsonArray("JsonArray.json");

    }

解析结果:

· 解析复杂Json

解析结果:

public static void parseJsonComposite(String filePath) throws FileNotFoundException {

        FileReader jsonReader = new FileReader(filePath);

        JsonParser parser = new JsonParser(); // 创建JSON解析器

        JsonObject jsonObject = (JsonObject) parser.parse(jsonReader);// 创建JsonObject对象

        System.out.println("code="+jsonObject.get("code").getAsInt());

        System.out.println("message=" + jsonObject.get("message").getAsString());

        JsonArray jsonArray = jsonObject.get("data").getAsJsonArray();// 得到为json的数组

        for (int i = 0; i < jsonArray.size(); i++) {

            System.out.println("---------------");

            JsonObject subObject = jsonArray.get(i).getAsJsonObject();

            System.out.println("name=" + subObject.get("name").getAsString());

            System.out.println("latinName=" + subObject.get("latinName").getAsString());

            System.out.println("type="+subObject.get("type").getAsString());

            System.out.println("id=" + subObject.get("id").getAsInt());

        }

    }

    public static void main(String[] args) throws FileNotFoundException {

        parseJsonComposite("JsonArray.json");

    }

2-2使用Gson解析

使用Google提供的Gson包解析Json数据是十分方便的,其采用了ORM思想:直接将Json数据映射到对象中去。

要想将元素与对象中属性一一对应,我们可以使用注解@SerializedName("元素名")

class InfoDetail {



        @SerializedName("name")

        private String name;

        @SerializedName("latinName")

        private String latinName;

        @SerializedName("type")

        private String type;

        @SerializedName("id")

        private int id;

        ...

    }

其中属性名可以和元素名不同,即使是Json中的数组或者其他嵌套元素也可以很方便地映射:

//包含InfoDetail对象

    class InfoComposite{

        ...

        @SerializedName("data")

        private ArrayList<InfoDetail> infoDetails=new ArrayList<InfoDetail>();

        ...

    }

· 解析Json对象

public static void main(String[] args) throws FileNotFoundException {

        FileReader jsonReader = new FileReader("JsonObject.json");

        JsonParser parser = new JsonParser(); // 创建JSON解析器

        JsonObject jsonObject = (JsonObject) parser.parse(jsonReader);// 创建JsonObject对象

        InfoDetail infoDetail=GsonUtil.parseJsonWithGson(jsonObject.toString(), InfoDetail.class);

        System.out.println("Gson解析Json对象:");

        System.out.println("---------------");

        System.out.println(infoDetail.getName());

        System.out.println(infoDetail.getLatinName());

        System.out.println(infoDetail.getType());

        System.out.println(infoDetail.getId());

        System.out.println("---------------");

    }

· 解析复杂Json

/*

    * 封装具有泛型参数的GSON解析工具类,方便对不同类的数据的转换

    */

    class GsonUtil {public static <T> T parseJsonWithGson(String jsonData, Class<T> type) {

        Gson gson = new Gson();

        T result = gson.fromJson(jsonData, type);

        return result;

        }

    }



    public static void main(String[] args) throws FileNotFoundException {



        FileReader jsonReader = new FileReader("JsonComposite.json");

        jsonObject = (JsonObject) parser.parse(jsonReader);// 创建JsonObject对象

        InfoComposite infoComposite=GsonUtil.parseJsonWithGson(jsonObject.toString(), InfoComposite.class);

        System.out.println("Gson解析复杂Json:");

        System.out.println("---------------");

        System.out.println("code="+infoComposite.getCode());

        System.out.println("message="+infoComposite.getMessage());

        System.out.println("infodetails="+infoComposite.getInfoDetails().size());

        System.out.println("---------------");

    }

解析结果:

全部代码:

package json;



    import java.io.FileNotFoundException;

    import java.io.FileReader;



    import com.google.gson.JsonArray;

    import com.google.gson.JsonObject;

    import com.google.gson.JsonParser;



    public class JsonHandler {



    public static void parseJsonObject(String filePath) throws FileNotFoundException{

        FileReader jsonReader = new FileReader(filePath);

        JsonParser parser = new JsonParser(); // 创建JSON解析器

        JsonObject jsonObject = (JsonObject) parser.parse(jsonReader);// 创建JsonObject对象

        System.out.println("---------------");

        System.out.println("name="+jsonObject.get("name").getAsString());

        System.out.println("latinName="+jsonObject.get("latinName").getAsString());

        System.out.println("type="+jsonObject.get("type").getAsString());

        System.out.println("id="+jsonObject.get("id").getAsString());

        System.out.println("---------------");

    }



    public static void parseJsonArray(String filePath) throws FileNotFoundException {

        FileReader jsonReader = new FileReader(filePath);

        JsonParser parser = new JsonParser(); // 创建JSON解析器

        JsonObject jsonObject = (JsonObject) parser.parse(jsonReader);// 创建JsonObject对象

        JsonArray jsonArray = jsonObject.get("data").getAsJsonArray();// 得到为json的数组

        for (int i = 0; i < jsonArray.size(); i++) {

            System.out.println("---------------");

            JsonObject subObject = jsonArray.get(i).getAsJsonObject();

            System.out.println("name=" + subObject.get("name").getAsString());

            System.out.println("latinName=" + subObject.get("latinName").getAsString());

            System.out.println("type="+subObject.get("type").getAsString());

            System.out.println("id=" + subObject.get("id").getAsInt());

        }

    }



    public static void parseJsonComposite(String filePath) throws FileNotFoundException {

        FileReader jsonReader = new FileReader(filePath);

        JsonParser parser = new JsonParser(); // 创建JSON解析器

        JsonObject jsonObject = (JsonObject) parser.parse(jsonReader);// 创建JsonObject对象

        System.out.println("code="+jsonObject.get("code").getAsInt());

        System.out.println("message=" + jsonObject.get("message").getAsString());

        JsonArray jsonArray = jsonObject.get("data").getAsJsonArray();// 得到为json的数组

        for (int i = 0; i < jsonArray.size(); i++) {

            System.out.println("---------------");

            JsonObject subObject = jsonArray.get(i).getAsJsonObject();

            System.out.println("name=" + subObject.get("name").getAsString());

            System.out.println("latinName=" + subObject.get("latinName").getAsString());

            System.out.println("type="+subObject.get("type").getAsString());

            System.out.println("id=" + subObject.get("id").getAsInt());

        }

    }



    public static void main(String[] args) throws FileNotFoundException {

        parseJsonObject("JsonObject.json");

        parseJsonArray("JsonArray.json");

        parseJsonComposite("JsonComposite.json");



        FileReader jsonReader = new FileReader("JsonObject.json");

        JsonParser parser = new JsonParser(); // 创建JSON解析器

        JsonObject jsonObject = (JsonObject) parser.parse(jsonReader);// 创建JsonObject对象

        InfoDetail infoDetail = GsonUtil.parseJsonWithGson(jsonObject.toString(), InfoDetail.class);

        System.out.println("Gson解析Json对象:");

        System.out.println("---------------");

        System.out.println(infoDetail.getName());

        System.out.println(infoDetail.getLatinName());

        System.out.println(infoDetail.getType());

        System.out.println(infoDetail.getId());

        System.out.println("---------------");

        jsonReader = new FileReader("JsonComposite.json");

        jsonObject = (JsonObject) parser.parse(jsonReader);// 创建JsonObject对象

        InfoComposite infoComposite = GsonUtil.parseJsonWithGson(jsonObject.toString(), InfoComposite.class);

        System.out.println("Gson解析复杂Json:");

        System.out.println("---------------");

        System.out.println("code=" + infoComposite.getCode());

        System.out.println("message=" + infoComposite.getMessage());

        System.out.println("infodetails=" + infoComposite.getInfoDetails().size());

        System.out.println("---------------");

        }



    /*

    * 封装具有泛型参数的GSON解析工具类,方便对不同类的数据的转换

    */

    class GsonUtil {public static <T> T parseJsonWithGson(String jsonData, Class<T> type) {

        Gson gson = new Gson();

        T result = gson.fromJson(jsonData, type);

        return result;

    }

    }



    class InfoComposite{



    private int code;

    private String message;

    @SerializedName("data")

    private ArrayList<InfoDetail> infoDetails=new ArrayList<InfoDetail>();



    public int getCode() {

        return code;

    }

    public void setCode(int code) {

        this.code = code;

    }

    public String getMessage() {

        return message;

    }

    public void setMessage(String message) {

        this.message = message;

    }

    public ArrayList<InfoDetail> getInfoDetails() {

        return infoDetails;

    }

    public void setInfoDetails(ArrayList<InfoDetail> infoDetails) {

        this.infoDetails = infoDetails;

    }



    }



    class InfoDetail {



    @SerializedName("name")

    private String name;

    @SerializedName("latinName")

    private String latinName;

    @SerializedName("type")

    private String type;

    @SerializedName("id")

    private int id;



    public int getId() {

        return id;

    }



    public String getName() {

        return name;

    }



    public String getLatinName() {

        return latinName;

    }



    public String getType() {

        return type;

    }



    public void setId(int id) {

        this.id = id;

    }



    public void setName(String name) {

        this.name = name;

    }



    public void setLatinName(String latinName) {

        this.latinName = latinName;

    }



    public void setType(String type) {

        this.type = type;

    }

    }

}