Reading JSON from a text file

前端 未结 7 1461
隐瞒了意图╮
隐瞒了意图╮ 2021-02-09 01:30

I know of some JSON libs around and I\'m currently looking into Google-JSON but all I want to achieve is something simple and I want to know what you would suggest.

I wa

7条回答
  •  再見小時候
    2021-02-09 02:06

    Install Google Gson and create those two model classes

    public class Data {
        private String name;
        private String title;
        private int currentMap;
        private List items;
        private int[][] map;
    
        public String getName() { return name; }
        public String getTitle() { return title; }
        public int getCurrentMap() { return currentMap; }
        public List 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 items) { this.items = items; }
        public void setMap(int[][] map) { this.map = map; }
    }
    

    and

    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; }
    }
    

    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
    

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

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

    And to get the name of the first Item:

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

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

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

    See also this answer for another complex Gson example.

提交回复
热议问题