如何使用javax.json包读取JSON文件?

时间:2016-09-30 08:08:06

标签: java json parsing

我相信我需要创建一个JsonReader对象并调用其中一个Json静态方法,但是我无法从我的file.json中读取。

创建阅读器方法似乎要求输入为字符串。我是否应该尝试将整个JSON文件解释为字符串?

1 个答案:

答案 0 :(得分:7)

假设您有文件person.json包含此类JSON数据:

{ 
    "name": "Jack", 
    "age" : 13, 
    "isMarried" : false,
    "address": { 
        "street": "#1234, Main Street", 
        "zipCode": "123456" 
    },
    "phoneNumbers": ["011-111-1111", "11-111-1111"]
}

使用javax.json,您可以这样解析此文件:

public class Example throws Exception {

    public static void main(String[] args) {
        InputStream fis = new FileInputStream("person.json");

        JsonReader reader = Json.createReader(fis);

        JsonObject personObject = reader.readObject();

        reader.close();

        System.out.println("Name   : " + personObject.getString("name"));
        System.out.println("Age    : " + personObject.getInt("age"));
        System.out.println("Married: " + personObject.getBoolean("isMarried"));

        JsonObject addressObject = personObject.getJsonObject("address");
        System.out.println("Address: ");
        System.out.println(addressObject.getString("street"));
        System.out.println(addressObject.getString("zipCode"));

        System.out.println("Phone  : ");
        JsonArray phoneNumbersArray = personObject.getJsonArray("phoneNumbers");

        for (JsonValue jsonValue : phoneNumbersArray) {
            System.out.println(jsonValue.toString());
        }
    }
}

另请参阅此问题:From JSON String to Java Object using javax.json