我已经使用Node.js和RESTful API创建了一个AsyncTask来检索数据。我在StringBuilder中存储输入,但问题是我想从结果中检索一个键:值对(Error : true/false
是特定的)。由于结果不是JSON形式,我不能使用.get("Element")
方法。这是我的AsyncTask:
class RegisterAsync extends AsyncTask<String , Void, Integer> {
@Override
protected Integer doInBackground(String... params) {
String toDO = params[0];
StringBuilder sb = new StringBuilder();
Boolean isError = false;
int toReturn;
try {
URL url = new URL("http://192.168.0.14:3030/api/insert");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
OutputStream os = con.getOutputStream();
os.write(toDO.getBytes());
os.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = "";
while((line = reader.readLine())!=null){
sb.append(line + '\n');
}
reader.close();
Log.d("RecvdToRegisterAsync: " , sb.toString());
//got result in sb... What next???
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
答案 0 :(得分:1)
您可以根据响应字符串将字符串转换为JSONObject或JSONArray。像这样:
JSONObject response = new JSONObject(sb.toString());
String key=response.get("key");
我希望它有所帮助。
答案 1 :(得分:0)
试试这个;)
jsonResponse = new String(serverResponse, "UTF-8");
JSONObject jObject = new JSONObject(jsonResponse);
JSONObject json= jObject.getJSONObject("data");
//there is the data in String format
String data= json.getString(objectToFind);