Reading JSON via android webservice

I am trying to create an android app web service to return a json file like:

{"success": 1, "message": "Post Available" "posts!": [{"Post_id": "1", "username": "Hasni", "title": "caption", "message" : "this is my post"}, {"post_id": "2", "username": "user2", "title": "titre 2", "message": "this is my post 2"}, {"post_id ":" 3 "," username ":" 123 "," title ":" 12 "," message ":" 111 "}, {" post_id ":" 4 "," username ":" 1212 ", "title": "1212", "post": "1212"}, {"post_id": "5", "username ":" 1212 "," title ":" Bonjour "," message ":" voila ce message qui vient d'une session "}, {" Post_id ":" 6 "," username ":" 121212 " , "title": "title", "message": "message"}]}

This is the piece of code to read this JSON:

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("receiver", strSender));
        JSONObject json = jsonParser.makeHttpRequest(
                LOGIN_URL, "POST", params);
        success = json.getInt(TAG_SUCCESS);

        Log.d("ok", "ok");

        if (success == 1){

            messagesArray = (JSONArray)json.getJSONArray(TAG_POSTS);
            for (int i= 0;i <messagesArray.length();i++){
                Log.d("iteration", "iteration" + i);
                JSONObject messageJson = messagesArray.getJSONObject(i);
                Log.d("post_id","post_id: "+i+ " "+ messageJson.getString(TAG_POSTS_ID) );
                Log.d("username","username: " +i+" " + messageJson.getString(TAG_POSTS_USERNAME));
                Log.d("title", "title: " +i+ " " + messageJson.getString(TAG_POSTS_ID_TITLE));
                Log.d("message","message: "+i+" "+ messageJson.getString(TAG_POSTS_ID_MESSAGE));
            }

        }else{
            Log.d("failed", "!!!!!!!!!!!!!!!!!!!!!!!!");
        }

      

But I have a problem: apps crash and exit. This is the logcat:

09-27 23: 15: 37.119: W / System.err (489): org.json.JSONException: No value for posts 09-27 23: 15: 37.119: W / System.err (489): when org.json .JSONObject.get (JSONObject.java:354) 09-27 23: 15: 37.128: W / System.err (489): at org.json.JSONObject.getJSONArray (JSONObject.java:544) 09-27 23: 15 : 37.128: W / System.err (489): at com.example.mysql.ReadMessages.onCreate (ReadMessages.java:73) 09-27 23: 15: 37.128: W / System.err (489): at android. app.Instrumentation.callActivityOnCreate (Instrumentation.java:1047) 09-27 23: 15: 37.128: W / System.err (489): at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:1611) 09-27 23: 15: 37.128: W / System.err (489): on android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:1663) 09-27 23: 15: 37.128: W / System.err (489): on android.app .ActivityThread.access $ 1500 (ActivityThread.java:117) 09-27 23: 15: 37.128: W / System.err (489): at android.app.ActivityThread $ H.handleMessage (ActivityThread.java:931) 09-27 23: 15: 37.138: W / System. err (489): on android.os.Handler.dispatchMessage (Handler.java:99) 09-27 23: 15: 37.138: W / System.err (489): on android.os.Looper.loop (Looper.java : 123) 09-27 23: 15: 37.138: W / System.err (489): at android.app.ActivityThread.main (ActivityThread.java:3683) 09-27 23: 15: 37.138: W / System.err (489): on java.lang.reflect.Method.invokeNative (native method) 09-27 23: 15: 37.138: W / System.err (489): on java.lang.reflect.Method.invoke (Method.java : 507) 09-27 23: 15: 37.138: W / System.err (489): at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run (ZygoteInit.java:839) 09-27 23: 15: 37.138 : W / System.err (489): at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:597) 09-27 23: 15: 37.138: W / System.err (489): with dalvik.system.NativeStart.main (native method)

+3


source to share


2 answers


I tried my code this way,

    private void jsonTest() {
    try {
        String jsonString = "{\"success\":1,\"message\":\"Post Available!\",\"posts\":[{\"post_id\":\"1\",\"username\":\"hasni\",\"title\":\"titre\",\"message\":\"this is my message\"},{\"post_id\":\"2\",\"username\":\"user2\",\"title\":\"titre 2\",\"message\":\"this is my message 2\"},{\"post_id\":\"3\",\"username\":\"123\",\"title\":\"12\",\"message\":\"111\"},{\"post_id\":\"4\",\"username\":\"1212\",\"title\":\"1212\",\"message\":\"1212\"},{\"post_id\":\"5\",\"username\":\"1212\",\"title\":\"bonjour\",\"message\":\"voila ce message qui vient d'une session \"},{\"post_id\":\"6\",\"username\":\"121212\",\"title\":\"titre\",\"message\":\"message\"}]}";

        Log.i(TAG, "jsonString = " + jsonString);
        JSONObject json = new JSONObject(jsonString);
        int success = json.getInt("success");

        Log.d("ok", "ok");

        if (success == 1) {

            JSONArray messagesArray = (JSONArray) json
                    .getJSONArray("posts");
            for (int i = 0; i < messagesArray.length(); i++) {
                Log.d("iteration", "iteration" + i);
                JSONObject messageJson = messagesArray.getJSONObject(i);
                Log.d("post_id",
                        "post_id: " + i + " "
                                + messageJson.getString("post_id"));
                Log.d("username",
                        "username: " + i + " "
                                + messageJson.getString("username"));
                Log.d("title",
                        "title: " + i + " "
                                + messageJson.getString("title"));
                Log.d("message",
                        "message: " + i + " "
                                + messageJson.getString("message"));
            }

        } else {
            Log.d("failed", "!!!!!!!!!!!!!!!!!!!!!!!!");
        }
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
}

      



And worked correctly, maybe there is something wrong with your TAGs that you defined.

+1


source


thinks the code is working correctly, but i is the origin of the problem in the json parser



package com.example.mysql;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    DefaultHttpClient httpClient = new DefaultHttpClient();
    List<Cookie> cookies = httpClient.getCookieStore().getCookies();


    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

      

-1


source







All Articles