【问题标题】:How change type of JSONObject when using javax使用 javax 时如何更改 JSONObject 的类型
【发布时间】:2021-05-28 21:47:30
【问题描述】:

我有一个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);==&gt; Cannot instantiate the type JsonObject

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

如何更正我的代码以使 JsonObject jsonObject = new JsonObject(response) 采用 String 并继续使用 javax.json.JsonObject 类?

【问题讨论】:

  • javadocs 解释您需要做什么。它表明这是interface 而不是class

标签: java arrays json jax-rs


【解决方案1】:

根据其 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();

【讨论】:

猜你喜欢
  • 2017-09-17
  • 1970-01-01
  • 1970-01-01
  • 2021-04-24
  • 1970-01-01
  • 2014-09-20
  • 2019-03-12
  • 1970-01-01
  • 2019-10-25
相关资源
最近更新 更多