JSON Parsing проблема с программой Android
У меня есть класс Android для разбора JSON
массив, как это, теперь проблема в том, что это только разбор 'image_first'
index Я тоже хочу разобрать 'image_second'. Но когда я попытаюсь разобрать image_second, он выдаст некоторые исключения
код
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText etResponse;
TextView tvIsConnected;
JSONObject jObject;
JSONArray jCountries = null;
String image_first;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// get reference to the views
etResponse = (EditText) findViewById(R.id.etResponse);
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
// check if you are connected or not
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are conncted");
}
else{
tvIsConnected.setText("You are NOT conncted");
}
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().execute("http://kodspider.com/Android_Test/index.php"/*"http://hmkcode.appspot.com/rest/controller/get.json"*/);
}
public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static 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;
}
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
try {
JSONObject json = new JSONObject(result);
String str = "";
JSONArray articles = json.getJSONArray("images");
str += "articles length = "+json.getJSONArray("images").length();
str += "\n--------\n";
str += "names: "+articles.getJSONObject(0).names();
str += "\n--------\n";
str += "url: "+articles.getJSONObject(0).getString("image_second");
etResponse.setText(str);
etResponse.setText(json.toString(1));
for(int i=0;i<json.getJSONArray("images").length();i++){
System.out.println(articles.getJSONObject(i).getString("image_second"));
}
// try {
// jObject = new JSONObject(result);
// // Retrieves all the elements in the 'countries' array
// jCountries = jObject.getJSONArray("images");
// for(int i=0;i<jCountries.length();i++){
// image_first = jCountries.getJSONObject(i).getString("image_first");
// }
// System.out.println(image_first);
// } catch (JSONException e) {
// e.printStackTrace();
// }
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
LogCat
05-14 12:19:15.700: W/System.err(581): org.json.JSONException: No value for image_second
05-14 12:19:15.700: W/System.err(581): at org.json.JSONObject.get(JSONObject.java:354)
05-14 12:19:15.700: W/System.err(581): at org.json.JSONObject.getString(JSONObject.java:510)
05-14 12:19:15.700: W/System.err(581): at com.hmkcode.android.MainActivity$HttpAsyncTask.onPostExecute(MainActivity.java:125)
05-14 12:19:15.710: W/System.err(581): at com.hmkcode.android.MainActivity$HttpAsyncTask.onPostExecute(MainActivity.java:1)
05-14 12:19:15.710: W/System.err(581): at android.os.AsyncTask.finish(AsyncTask.java:417)
05-14 12:19:15.710: W/System.err(581): at android.os.AsyncTask.access$300(AsyncTask.java:127)
05-14 12:19:15.710: W/System.err(581): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
05-14 12:19:15.720: W/System.err(581): at android.os.Handler.dispatchMessage(Handler.java:99)
05-14 12:19:15.720: W/System.err(581): at android.os.Looper.loop(Looper.java:123)
05-14 12:19:15.720: W/System.err(581): at android.app.ActivityThread.main(ActivityThread.java:4627)
05-14 12:19:15.720: W/System.err(581): at java.lang.reflect.Method.invokeNative(Native Method)
05-14 12:19:15.730: W/System.err(581): at java.lang.reflect.Method.invoke(Method.java:521)
05-14 12:19:15.730: W/System.err(581): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-14 12:19:15.730: W/System.err(581): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-14 12:19:15.730: W/System.err(581): at dalvik.system.NativeStart.main(Native Method)
2 ответа
Решение
Попробуйте заменить эту строку:
str += "url: "+articles.getJSONObject(0).getString("image_second");
С этим:
str += "url: "+articles.getJSONObject(2).getString("image_second");
ИЛИ ЖЕ
str += "url: "+articles.getJSONObject(3).getString("image_second");
{
"images": [
{
"image_first": "http://kodspider.com/Android_Test/images/bg.jpg"
},
{
"image_first": "http://kodspider.com/Android_Test/images/gmail_bg.jpg"
},
{
"image_second": "http://kodspider.com/Android_Test/images/bbg.jpg"
},
{
"image_second": "http://kodspider.com/Android_Test/images/1425328_405486846250283_806381377_o.jpg"
}
]
}
Изменить это
for(int i=0;i<json.getJSONArray("images").length();i++){
System.out.println(articles.getJSONObject(i).getString("image_second"));
}
к
JSONArray articles = json.getJSONArray("images");
JSONObject jb = articles.getJSONObject(0);
String imageurl1 = jb.getString("image_first");
JSONObject jb1 = articles.getJSONObject(1);
String imageurl2 = jb1.getString("image_first");
JSONObject jb2 = articles.getJSONObject(2);
String imageurl3 = jb2.getString("image_second");
JSONObject jb3 = articles.getJSONObject(3);
String imageurl4 = jb3.getString("image_second");