【问题标题】:How do I use the output of a JSON file in Java for creating an object with it? [duplicate]如何使用 Java 中 JSON 文件的输出来创建对象? [复制]
【发布时间】:2016-08-19 04:47:07
【问题描述】:

为了一个学校项目,我不得不用 Java 编写一个小游戏。 游戏是 RushHour,你可以在这里看到它的一个例子:http://www.thinkfun.com/play-online/rush-hour/

我的老师现在要求我允许我的代码读取外部文件,以便游戏的初始状态不再在我的 main 中硬编码,并且可以自定义游戏的参数(棋盘的大小,游戏中的汽车数量...)

这是我的第一个 JSON 文件,它设置了一款经典游戏。

{
"ClassicBoard" :
        {
            "height" : "6",
            "width"  : "6",
             "exit":
                 {
                   "row" : "2",
                   "column" : "5"
                 }
        },
"ListOfCars" :
        {
            "car2" :
                {
                   "char" : "2",
                   "size" : "3",
                   "orientation" : "vertical",
                   "currentPosition":
                            {
                             "row" : "2",
                             "column": "2"
                            }
                },            
            "car3"  :
                {
                "char" : "3",
                "size" : "3",
                "orientation" : "vertical",
                "currentPosition":
                            {
                             "row" : "2",
                             "column": "4"
                            }
                }
        },
"redCar":
        {
         "char" : "1",
         "size" : "2",
         "orientation" : "horizontal",
         "currentPosition":
            {
              "row" : "2",
              "column": "0"
            }
        }

}

我试图找到如何读取文件并重用它的输出来创建 RushHourGame 对象。这是构造函数。

public RushHourGame(Board board, List <Car> cars, Car redCar) throws RushHourException
{
    this.board = board;
    this.redCar = redCar;

    if(((redCar.getOrientation() == Orientation.HORIZONTAL)
            && (board.getExit().getRow() != redCar.getCurrentPosition().getRow()))
            || (((redCar.getOrientation() == Orientation.VERTICAL)
            && (board.getExit().getColumn() != redCar.getCurrentPosition().getColumn()))))
    {
        throw new RushHourException("Car must be aligned with the exit, "
                + "a default game has been created");
    }
    board.put(redCar);
    for (Car putCars : cars)
    {
        board.put(putCars);
    }
}

我尝试使用 BufferedReader,像这样。

public static String readFile(String filename)
{
    String result ="";
    try
    {
        BufferedReader br = new BufferedReader (new FileReader(filename));
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();
        while (line != null)
        {
            sb.append(line);
            line = br.readLine();
        }
        result = sb.toString();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    return result;
}

但我不知道如何使用它来解析我的 JSON 文件。有人可以帮助我吗?

【问题讨论】:

    标签: java json parsing buffer reader


    【解决方案1】:

    您的问题的多个答案可以找到here。我更喜欢 StaxMan 提供的答案:

    最简单的选择是Jackson

    MyObject ob = new ObjectMapper().readValue(jsonString, RushHourState.class);
    

    上面的代码应该使用下面提供的 Java POJO 自动处理 JSON/Java 对象绑定:

    public class RushHourState {
       private ArrayList<Car> listOfCars;
       private ClassicBoard classicBoard;
       private Car redCar;
    
       public ArrayList<Car> getListOfCars() {
           return listOfCars;
       }
       public void setListOfCars(ArrayList<Car> listOfCars) {
           this.listOfCars = listOfCars;
       }
       public ClassicBoard getClassicBoard() {
           return classicBoard;
       }
       public void setClassicBoard(ClassicBoard classicBoard) {
           this.classicBoard = classicBoard;
       }
       public Car getRedCar() {
           return redCar;
       }
       public void setRedCar(Car redCar) {
           this.redCar = redCar;
       }
    }
    
    // ---------------------------------------------------
    
    public class ClassicBoard {
       private int height;
       private int width;
       private HashMap<String, String> exit;
       public int getHeight() {
        return height;
       }
       public void setHeight(int height) {
        this.height = height;
       }
       public int getWidth() {
        return width;
       }
       public void setWidth(int width) {
        this.width = width;
       }
       public HashMap<String, String> getExit() {
        return exit;
       }
       public void setExit(HashMap<String, String> exit) {
        this.exit = exit;
       }
    }
    
    // ---------------------------------------------------
    
    public class Car {
        private int charr;
        private int size;
        private String orientation;
        private HashMap<String, String> currentPosition;
        public int getCharr() {
            return charr;
        }
        public void setCharr(int charr) {
            this.charr = charr;
        }
        public int getSize() {
            return size;
        }
        public void setSize(int size) {
            this.size = size;
        }
        public String getOrientation() {
            return orientation;
        }
        public void setOrientation(String orientation) {
            this.orientation = orientation;
        }
        public HashMap<String, String> getCurrentPosition() {
            return currentPosition;
        }
        public void setCurrentPosition(HashMap<String, String> currentPosition) {
            this.currentPosition = currentPosition;
        }
    }
    

    注意:我将 Car 类中的变量“char”重命名为“charr”,因为 char 是 Java 保留关键字。希望对您有所帮助!

    【讨论】:

    • 感谢您的回答。您的回答看起来很有趣,我会尽快详细检查,如果有效,我会回电话给您!
    • 嗯,我认为代码不是很有帮助,因为我已经为 Car、Board、Position...另外,我认为使用 setter 不是解决方案,因为我不希望用户有可能更改这些值。 RushHourGame 类的构造函数调用了所有其他类的 cnstructor,因此,我只需要 RushHourGame 的构造函数来检索 JSON 文件中的数据和值,并用它创建一个新的 RushHourGame 对象。但感谢杰克逊的解决方案。
    猜你喜欢
    • 2015-11-13
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    • 2017-04-19
    • 2021-04-25
    相关资源
    最近更新 更多