正在使用 Gson 解析 JSON 文件

Parsing JSON File using Gson

我有 JSON 如下所示的文件:

{
    "inventory": [ 
        ...
    ],
    "services": {
        "M": 2,
        "Moneypenny": 2,
        "intelligence": [
            {
                "missions": [
                    ...
                ]
            },
            {
                "missions": [
                    ...
                ]
            }
        ],
        "time": 25
    }
} 

我想解析 JSON 中的服务。 我设法通过使用 JsonArray 获取它来解析库存。 这就是我做服务部分的方式:

JsonElement MinstancesJson = p.parse(file).getAsJsonObject().getAsJsonObject("services").get("M");
int Minstances = MinstancesJson.getAsInt();

但是我的程序在第一行就崩溃了。

这是在我的系统中 运行 完美的工作代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import com.google.gson.JsonElement;
import com.google.gson.JsonIOException;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;

public class EntityName {

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

        File f = new File("others//entity-name.json");
        JsonParser jsonParser = new JsonParser();
        JsonElement jsonElement = jsonParser.parse(new FileReader(f));
        JsonElement element = jsonElement.getAsJsonObject().getAsJsonObject("services").get("M");
        System.out.println(element.getAsInt());
    }

}

此处实体-name.json包含给定的json.

您必须为 json 中的每个项目创建一个 class。

因此,您将创建 class Inventory、class Services、class Intelligence 和 class Missions

例如classServices会是这样的:

public class Services {

    int m;
    int moneyPenny;
    List<Intelligence> intelligenceList;
    int time;

    //Constructor, getter and setter

}

请注意 intelligenceListIntelligente 个对象的列表。

毕竟,使用com.google.gson.Gson库,你可以通过fromJson方法解析你的json。这样,你将得到一个Inventory对象。