通过webservice android读取JSON

时间:2014-09-27 00:14:00

标签: java android json webservice-client arrays

我尝试开发一个Android应用程序Web服务来返回一个json文件,例如:

  

{"成功":1,"消息":"邮政   !可用#&34;,"帖子":[{" POST_ID":" 1""用户名":"哈斯尼& #34;"标题":"滴度""消息":"此   是我的消息"},{" post_id":" 2","用户名":"用户2","标题& #34;:"滴度   2","消息":"这是我的消息   2"},{" POST_ID":" 3""用户名":" 123""标题&#34 ;:" 12""消息":" 111"},{" POST_ID":" 4",& #34;用户名":" 1212""标题":" 1212""消息":" 1212&# 34;},{" POST_ID":" 5""用户名":" 1212""标题&#34 ;: "的Bonjour""消息":"瞧   ce message qui vient d' une session   "},{" POST_ID":" 6""用户名":" 121212""标题&#34 ;:"滴度""消息":"消息"}]}

这是阅读此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", "!!!!!!!!!!!!!!!!!!!!!!!!");
        }

但我有一个问题:应用程序崩溃并退出。这是logcat:

  

09-27 23:15:37.119:W / System.err(489):org.json.JSONException:No   09-27 23:15:37.119:W / System.err(489):at   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):at   android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)   09-27 23:15:37.128:W / System.err(489):at   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):at   android.os.Handler.dispatchMessage(Handler.java:99)09-27   23:15:37.138:W / System.err(489):at   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):at   java.lang.reflect.Method.invokeNative(Native Method)09-27   23:15:37.138:W / System.err(489):at   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):at   dalvik.system.NativeStart.main(原生方法)

2 个答案:

答案 0 :(得分:1)

我用这种方式尝试了你的代码,

    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();
    }
}

并且工作正常,您定义的TAG可能有问题。

答案 1 :(得分:-1)

认为代码工作正常但是 我这个问题的根源在于json解析器

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;

    }
}