如何解析json分支值

时间:2014-09-05 07:40:48

标签: java android json eclipse android-emulator

我是Android编程的新手。我试图通过解析它在我的Android应用程序中干预用户ID的值,但错误说没有用户的值。如何从android中的json数据中获取输入?我在下面附上了我的logcat错误。任何人都可以帮帮我吗?先谢谢

"status": "SUCCESS",
"msg": "Login Successful",
"data": {
    "user": {
        "id": "6",
        "first_name": "e",
        "last_name": "ff",
        "address": "dr",
        "mobile": "55",
        "email": "rokes1990@live.com",
        "password": "4124bc0a9335c27f086f24ba207a4912",
        "pwd_reset_key": "",
        "name_on_card": "",
        "card_number": "",
        "expiry_date": "",
        "cvv": "",
        "tdatetime": "2014-07-11 02:55:08"
    }
}

LogCat错误:

09-05 03:36:00.567: D/dalvikvm(2227): GC_FOR_ALLOC freed 379K, 8% free 5765K/6220K, paused 76ms, total 82ms
09-05 03:36:02.077: W/Response(2227): {"GET":[],"POST":{"action":"login","app_secret":"jkhljkUILJGJkljhkjUGLG87796587687HGKJhghkjKUYGKJHjhgjUYGKUY7865876hgKUYGK","email":"rokes1990@live.com","password":"aa"},"status":"SUCCESS","msg":"Login Successful","data":{"user":{"id":"6","first_name":"e","last_name":"ff","address":"dr","mobile":"55","email":"rokes1990@live.com","password":"4124bc0a9335c27f086f24ba207a4912","pwd_reset_key":"","name_on_card":"","card_number":"","expiry_date":"","cvv":"","tdatetime":"2014-07-11 02:55:08"}}}
09-05 03:36:02.107: W/System.err(2227): org.json.JSONException: No value for user
09-05 03:36:02.117: W/System.err(2227):     at org.json.JSONObject.get(JSONObject.java:355)
09-05 03:36:02.117: W/System.err(2227):     at org.json.JSONObject.getString(JSONObject.java:515)
09-05 03:36:02.147: W/System.err(2227):     at example.atlcitylimo.Main.postLoginData(Main.java:116)
09-05 03:36:02.147: W/System.err(2227):     at example.atlcitylimo.Main.onClick(Main.java:181)
09-05 03:36:02.147: W/System.err(2227):     at android.view.View.performClick(View.java:4438)
09-05 03:36:02.147: W/System.err(2227):     at android.view.View$PerformClick.run(View.java:18422)
09-05 03:36:02.147: W/System.err(2227):     at android.os.Handler.handleCallback(Handler.java:733)
09-05 03:36:02.147: W/System.err(2227):     at android.os.Handler.dispatchMessage(Handler.java:95)
09-05 03:36:02.147: W/System.err(2227):     at android.os.Looper.loop(Looper.java:136)
09-05 03:36:02.157: W/System.err(2227):     at android.app.ActivityThread.main(ActivityThread.java:5017)
09-05 03:36:02.157: W/System.err(2227):     at java.lang.reflect.Method.invokeNative(Native Method)
09-05 03:36:02.157: W/System.err(2227):     at java.lang.reflect.Method.invoke(Method.java:515)
09-05 03:36:02.157: W/System.err(2227):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
09-05 03:36:02.157: W/System.err(2227):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
09-05 03:36:02.157: W/System.err(2227):     at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:1)

 protected String getId(String result) { 
    try {
    JSONObject jsonObject = new JSONObject(result);
    JSONObject data = new JSONObject(jsonObject.getString("data"));
    JSONObject user = new JSONObject(jsonObject.getString("user"));
    String id = user.getString("id");
    return id;
    }catch (Exception e) {
     Log.d("error", e.getLocalizedMessage());
   }
   return null;

}

答案 1 :(得分:0)

您可以使用Volley解析json字符串。检查"发出JSON请求"在以下链接中:

http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

Volley提供了一个简单的json请求。如果您希望响应中有json对象,则应使用JsonObjectRequest类,或者如果响应是json数组,则应使用JsonArrayRequest类。 StringRequest类将用于获取任何类型的字符串数据。响应可以是json,xml,html或纯文本。

您可以从JsonObjectRequest开始获取JSONObject:

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, url, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        //response is the JSONObject that you get from the request
                        //you can play with that request to get the exact info you want
                        String status = response.getString("status");
                        String msg = response.getString("msg");
                        JSONObject data = null;
                        try{
                            data = response.getJSONObject("data"); 
                        }catch (JSONException e1) {
                             e1.printStackTrace();
                        } 

                        JSONObject user = null;
                        try{
                            user = data.getJSONObject("user"); 
                        }catch (JSONException e1) {
                             e1.printStackTrace();
                        } 

                        String id = user.getString("id");
                        String first_name = user.getString("first_name");
                        //and goes on for the rest of the user info
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                    }
                });

此外,您还需要将此请求添加到请求队列

// Adding request to request queue
AppController.getInstance().addToRequestQueue(req, tag_json_arry);

您的AppController类如下:

import android.app.Application;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class AppController extends Application {

    public static final String TAG = AppController.class
            .getSimpleName();

    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;

    private static AppController mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized AppController getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public ImageLoader getImageLoader() {
        getRequestQueue();
        if (mImageLoader == null) {
            mImageLoader = new ImageLoader(this.mRequestQueue,
                    new LruBitmapCache());
        }
        return this.mImageLoader;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

最后在您的Manifest.xml中添加以下版本<application>标记

<application
        android:name="info.androidhive.volleyexamples.app.AppController"