我很抱歉,但我刚接触android编程,所以这看起来像是一个非常愚蠢的问题。
我建立了与我的JSON数据的连接,但我只需要获取我需要的数据,而不是所有不必要的数据。我的Json看起来像这样:
数据 “:[{” ID “:1,” 温度 “:” 21.375" , “湿度”: “28”}
这里我只需要id:1,温度:21.375,湿度:28
建立连接我有以下方法:
private class jsonConnection extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
String username = "websiteUsername";
String password = "websitePassword";
String credentials = username + ":" + password;
String sensorID = "1";
String api = "api";
String websiteURL = "https://" + credentials + "@website.com" + "/" + sensorID + "/" + api;
String credBase64 = Base64.encodeToString( credentials.getBytes(), Base64.DEFAULT ).replace( "\n", "" );
try {
URL url = new URL( websiteURL );
System.out.println( url );
System.out.println( credentials );
System.out.println( websiteURL );
connection = (HttpsURLConnection) url.openConnection();
String basicAuth = "Basic " + new String( encodeBase64URLSafeString( credentials.getBytes() ) );
connection.setRequestProperty( "Authorization", basicAuth );
connection.setRequestMethod( "GET" );
connection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded" );
connection.setRequestProperty( "Content-Language", "en-US" );
connection.setUseCaches( false );
connection.setDoInput( true );
connection.setDoOutput( true );
connection.connect();
InputStream stream = connection.getInputStream();
bufferedReader = new BufferedReader( new InputStreamReader( stream ) );
//StringBuffer buffer = new StringBuffer();
String line = "";
while (line != null) {
line = bufferedReader.readLine();
data = data + line;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog( MainActivity.this );
pd.setMessage( "Please wait" );
pd.setCancelable( false );
pd.show();
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute( result );
if (pd.isShowing()) {
pd.dismiss();
}
ScrollingMovementMethod());
System.out.println( data );
json_string = data;
System.out.println( "json_string: " + json_string );
}
}
我想我必须做这样的事情,但我不确定如何继续。
try {
JSONObject parentObject = new JSONObject( data );
JSONArray parentArray = parentObject.getJSONArray( "data" );
JSONObject finalObject = parentArray.getJSONObject( 0 );
int idName = finalObject.getInt( "id" );
int tempName = finalObject.getInt( "temperature" );
int humName = finalObject.getInt( "humidity" );
String batName = finalObject.getString( "battery" );
String modeName = finalObject.getString( "mode" );
String dateName = finalObject.getString( "date_time" );
String timeName = finalObject.getString( "date_time" );
String luxName = finalObject.getString( "lux" );
System.out.println( idName + tempName + humName + batName + modeName + dateName + timeName + luxName );
} catch (JSONException e) {
e.printStackTrace();
}
我怀疑它不应该是参数中的数据,但也许是别的东西,也许这会解决它?
JSONObject parentObject = new JSONObject( data );