首页 > 解决方案 > 使用 javax 时如何更改 JSONObject 的类型

问题描述

我有一个StringBuilder

我的代码如下:

String response = sb.toString();
// logger.info("response is '{}' ", response);
                         
JsonObject jsonObject = new JsonObject(response);
JsonObject fileStatuses = jsonObject.getJsonObject("FileStatuses");
JsonArray fileStatus = (JsonArray) fileStatuses.getJsonArray("FileStatus");
                    
for (int i = 0; i < fileStatus.size(); ++i) {
    JsonObject rec = fileStatus.getJsonObject(i);                   
    String pathSuffix = rec.getString("pathSuffix");
    logger.info(" the pathSuffix value is '{}' ", pathSuffix );
}

我想使用javax.json.JsonObject而不是org.json.JsonObject。所以,问题出在new JsonObject(response); ==> Cannot instantiate the type JsonObject.

我知道它org.json.JSONObject有一个接受字符串的构造函数,但我认为使用javax.json.JsonObject.

如何更正我的代码以 JsonObject jsonObject = new JsonObject(response)获取字符串并继续使用javax.json.JsonObject类?

标签: javaarraysjsonjax-rs

解决方案


根据它的 API 而不是使用JsonObject jsonObject = new JsonObject(response);你可以response像这样从你的 -String 实例化它:

String response = sb.toString();

StringReader reader = new StringReader(response);
JsonReader jsonReader = Json.createReader(reader);
JsonObject jsonObject = jsonReader.readObject();
jsonReader.close();

推荐阅读