我想"result"从下面的JSON响应中获取值并将其存储在本地.这是代码:
private class GetContacts extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
//JSONArray contacts;
contacts = jsonObj.getJSONArray("response");
Log.d("Response: ", "> " + contacts);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data …Run Code Online (Sandbox Code Playgroud) NSString *data = [NSString stringWithFormat:@"username=%@&password=%@",usertxt.text,pwdtxt.text,[NSNumber numberWithBool:YES]];
NSData *postData = [data dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
Run Code Online (Sandbox Code Playgroud)
//预先发送URL请求以发送数据.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSString *url = [NSString stringWithFormat:URL_PATH];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Accept"];
[request setHTTPBody:postData];
[request setTimeoutInterval:7.0];
NSURLResponse *_response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&_response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
Run Code Online (Sandbox Code Playgroud)
//打印服务器响应
NSLog(@"Login response:%@",str);
Run Code Online (Sandbox Code Playgroud)
//将JSON字符串解析为NSDictionary
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:urlData
options:kNilOptions
error:&error];
Run Code Online (Sandbox Code Playgroud)