【问题标题】:Can't convert org.json.JSONArray to JSONObject无法将 org.json.JSONArray 转换为 JSONObject
【发布时间】:2018-02-04 14:36:22
【问题描述】:

我正在尝试为我的 m8 服务器取得高分,但我遇到了一个问题:我无法将 JSONArray 转换为 JSONObject...我试图更改它们,但它不起作用,我可以'找不到从没有“名称”的 JSON 读取数据的方法。

【问题讨论】:

  • 您是否首先搜索过答案?这是一个非常常见的问题 :) stackoverflow.com/questions/7193599/…
  • 是的,我已经尝试过了,但我找到的主题都没有帮助我。 Nether 做到了。
  • 您的问题解决了吗?

标签: java android json


【解决方案1】:

这可能对你有帮助。

public class API {
    private String endpoint = "https://api.minesca.pe";
    private Context context;
    private String args;
    private HTTPRequest.StatusCode statusCode;
    private String jsonString;

    public API(Context context, String args) throws JSONException {
        this.context = context;
        this.args = args;
        fetch();
    }

    private void fetch() throws JSONException {
        HTTPRequest httpRequest = NetworkStack.getInstance(context).performRequest(endpoint + args, Request.Method.GET);
        statusCode = httpRequest.getStatusCode();
        if (statusCode == HTTPRequest.StatusCode.FOUND) {
            jsonString = httpRequest.getOutput();
        }
    }

    public JSONObject getJsonObject() {
        try {
            return new JSONObject(jsonString);
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

    public JSONArray getJsonArray() {
        try {
            return new JSONArray(jsonString);
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

    public HTTPRequest.StatusCode getStatusCode() {
        return statusCode;
    }
}

private JSONObject getJsonObjectFromAPI() throws APIError, JSONException {
        API api = new API(context, getAPIEndpoint());

        if (api.getStatusCode() == StatusCode.FOUND) {
            return api.getJsonObject();
        } else {
            throw new APIError("Unexpected response from the server.");
        }
    }
    private JSONArray getJsonArrayFromAPI() throws APIError, JSONException {
        API api = new API(context, getAPIEndpoint());

        if (api.getStatusCode() == StatusCode.FOUND) {
            return api.getJsonArray();
        } else {
            throw new APIError("Unexpected response from the server.");
        }
    }

【讨论】:

  • 谢谢。它确实帮助了我很多!
  • 太棒了!哥们点赞!
猜你喜欢
  • 2013-06-30
  • 2018-05-12
  • 2014-02-03
  • 2017-01-03
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
相关资源
最近更新 更多