【发布时间】:2016-05-13 19:02:15
【问题描述】:
我的网址是:http://a.nextput.com/apps/init/4/a/9fe2d2cbaa8332a4633be17b79208181-2y-10-ELVM4HwkaYaCVu6203Zjfus-G/o?aff_id={aff_id}
它包含单个对象{"success":true}。如何解析 url 并将 json 数据存储在变量中?
我的 doInBackground 方法:
protected Void doInBackground(Void... unused) {
String json = "";
URL url;
HttpURLConnection connection = null;
try {
url = new URL("http://a.nextput.com/apps/init/4/a/9fe2d2cbaa8332a4633be17b79208181-2y-10-ELVM4HwkaYaCVu6203Zjfus-G/o?aff_id=");
connection = (HttpURLConnection) url.openConnection();
InputStream inputStream = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data != -1) {
char currentChar = (char) data;
data = reader.read();
json += currentChar;
}
}catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
return json;
JSONObject jsonObject = new JSONObject(json);
boolean state = jsonObject.getBoolean("success");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("state",state);
editor.commit();
return null;
}
返回json;它显示不兼容的类型,并且在 JSONObject 中显示未处理的异常:org.json.JSONException。如何解决?
【问题讨论】:
-
有很多可用的 json 解析示例...请先尝试它们..
-
@RavindraKushwaha 它不是您建议的问题的副本。我试过json解析。但在这里它只是一个对象,这也是响应。我很困惑如何在这个 url 中执行解析。请帮忙。
-
你有什么尝试@himanshutiwari ...??像 JsonObject jsonobject = new JsonObject("here is yours response"); 这样的简单用法而不是 String sucess= jsonobject.getBoolean("success");
-
@RavindraKushwaha 我已经编辑了问题并展示了我尝试过的内容。它给出了一些错误。我在最后也提到了它们。请帮我解决它们。
标签: android json parsing android-asynctask