且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从文本文件中读取JSON

更新时间:2023-01-17 16:39:33

安装 Google Gson 并创建这两个模型类

Install Google Gson and create those two model classes

public class Data {
    private String name;
    private String title;
    private int currentMap;
    private List<Item> items;
    private int[][] map;

    public String getName() { return name; }
    public String getTitle() { return title; }
    public int getCurrentMap() { return currentMap; }
    public List<Item> getItems() { return items; }
    public int[][] getMap() { return map; }

    public void setName(String name) { this.name = name; }
    public void setTitle(String title) { this.title = title; }
    public void setCurrentMap(int currentMap) { this.currentMap = currentMap; }
    public void setItems(List<Item> items) { this.items = items; }
    public void setMap(int[][] map) { this.map = map; }
}

public class Item {
    private String name;
    private int x;
    private int y;

    public String getName() { return name; }
    public int getX() { return x; }
    public int getY() { return y; }

    public void setName(String name) { this.name = name; }
    public void setX(int x) { this.x = x; }
    public void setY(int y) { this.y = y; }
}

并按如下方式转换您的JSON:

And convert your JSON as follows:

Data data = new Gson().fromJson(json, Data.class);

要获得标题,请执行以下操作:

To get the title just do:

System.out.println(data.getTitle()); // Map One

并获取x = 3和y = 3的地图项目:

And to get the map item at x=3 and y=3:

System.out.println(data.getMap()[3][3]); // 1

并获取第一个项目的名称

System.out.println(data.getItems().get(0).getName()); // Pickaxe

简单!使用 Gson#toJson()转换另一种方式也很简单。

Easy! Converting the other way on is also simple using Gson#toJson().

String json = new Gson().toJson(data);

参见这个答案另一个复杂的Gson例子。

See also this answer for another complex Gson example.