我要感谢这个社区中的所有用户,是他们帮助我取得了今天的项目成就。
我现在再次需要你的帮助。到目前为止,我可以通过此 JSON 链接在我的项目中建立连接(出于隐私考虑已删除)
问题是我只能解析一个字符串,(firstName)
这是我的代码:
public class JSONActivity extends Activity {
static TextView http;
HttpClient client;
JSONObject json;
final static String URL = "REMOVED FOR PRIVACY CONCERNS
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
http = (TextView) findViewById(R.id.http);
client = new DefaultHttpClient();
new Read().execute("firstName");
}
public JSONObject getpw(String password) throws ClientProtocolException,
IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
url.append(password);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONObject getname = new JSONObject(data);
return getname;
} else {
Toast.makeText(JSONActivity.this, "error", Toast.LENGTH_SHORT);
return null;
}
}
public class Read extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
json = getpw("trustme");
return json.getString("firstName");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
http.setText(result);
}
}
}
我的问题是,如何解析多个字符串而不仅仅是“firstName”?
最佳答案
您可以通过执行以下操作获得这一切:
String firstname = json.getString("firstName");
String lastname = json.getString("lastName");
int checkedIn = json.getInt("checkedIn");
int updated = json.getInt("checkedindatetime");
JSONObject address = json.getJSONObject("address");
String streetaddress = address.getString("streetAddress");
String city = address.getString("city");
etc...
JSONArray phoneNumbers = json.getJSONArray("phoneNumber");
String type = phoneNumbers.getJSONObject(0).getString("type");
etc...
希望这对您有所帮助。
查看 json 的好资源,是这个 validator .
关于android - 解析多个 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9689581/