1

我正在使用 Java 解析来自服务器的 JSON 响应。我的最终目标是将结果中的数据存储在一个数组中。目前我正在使用它来尝试获得结果:

JSONArray jArray = myResponse.getJSONArray("results");

此代码失败,因为它正在寻找对象数组,而不是字符串数组:

org.json.JSONException: Value blah at 0 of type java.lang.String cannot be converted to JSONObject

这是我服务器的 JSON 响应:

{
  status: "OK",
  results: [
    "blah",
    "bleh",
    "blah"
  ]
}

有没有一种简单的方法可以将“结果”值放入数组中?或者我应该只写自己的解析器。

谢谢

- - - - - 更新 - - - - -

看起来我的问题实际上发生在其他地方,而不是 JSON 属性“结果”被转换为 JSONArray 的地方。

抱歉,感谢您的回答,他们帮助我意识到我找错了地方。

4

2 回答 2

5

这应该是它。因此,您可能试图在结果数组中获取 JSONObject 而不是 String。

JSONObject responseObject = new JSONObject(responseString);
JSONArray resultsArray = responseObject.getJSONArray("results");
for (int i=0; i<resultsArray.length(); i++)
    String resultString = resultsArray.getString(i);
于 2013-07-26T14:20:41.397 回答
0

由于您可能会有更多的属性,而不仅仅是String[] result,我建议像这样定义一个DTO

public class Dto {
    //of course you should have private fields and public setters/getters, but this is only a sample
    public String status;
    public List<String> results;//this can be also an array
}

然后在您的代码中:

ObjectMapper mapper = new ObjectMapper();
Dto dto = mapper.readValue(inputDtoJson, Dto.class);//now in dto you have all the properties you need
于 2013-07-26T15:37:01.750 回答