【发布时间】:2014-11-30 13:04:09
【问题描述】:
我正在构建一个 Android 应用程序,用户在其中输入一个值,例如 name 和 emailId,这个值被解析为一个 URL,作为响应我得到 作为该用户的主键的用户 ID。
我以带有成功消息的数组形式获得 ID。喜欢
这个 - {"message" : "succefull", "userID":"34341390ssvjsv"}.
现在我需要将此用户 ID 保存在该数组中的字符串中。
如何将这个ID“34341390ssvjsv”存储在字符串中?
这里是代码 -
private class DownloadJSON extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
}
@Override
protected String doInBackground(String... params) {
InputStream inputStream = null;
String result = "";
// Create an array
// public String postData() {
HttpClient httpclient = new DefaultHttpClient();
String URl = "http://url/api/user";
HttpPost httppost = new HttpPost(URl);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
3);
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("email", email));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new
InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
}
在上面关于 toast 结果的代码中,我得到 {"message" : "succefull", "userID":"34341390ssvjsv"}
【问题讨论】:
-
String example = "34341390ssvjsv" -
谢谢@m0skit0 我已经编辑了我的问题,请帮助我是 android 新手
-
你收到的是一个 JSON 字符串,检查一下。
-
我得到 {"message" : "succefull", "userID":"34341390ssvjsv"} 结果现在我只需要它的用户ID 以不同的字符串,以便我可以将其保存在共享首选项中
-
是的。那是一个 JSON 字符串。寻找库来处理这些字符串。如果您不想使用 JSON 库,请使用
indexOf和substring方法获取该字符串。