How to decode JSON values in my Android Aplication?

前端 未结 3 1517
死守一世寂寞
死守一世寂寞 2020-12-12 05:57

Hello guys I\'m trying to decode a JSON value into my Android Application, But I\'m not really sure What Am I doing wrong in my code...

This is my PHP file:

相关标签:
3条回答
  • 2020-12-12 06:45

    I will try to answer :-

    1. As per your code you have this String ["1","Admin","123","Adm","messages","0"] which is clearly a jsonarray but you are parsing as jsonobject in android.

    2. as @Boban said you must not run network operations on main thread so avoid dat.

    Now taking the response as what i mentioned in 1 here is how you will do :-

    JSONArray jArray=new JSONArray(json_str)
    String id=jArray.getString(0);
    String admin=jArray.getString(1);
    .
    .
    .
    

    Hope it helps ... and if i m wrong please correct me :)

    thx

    0 讨论(0)
  • 2020-12-12 06:46

    There are a couple of options for you available to achieve this.

    Personally i like to use the built in JSON parser in Android

    JSONObject jObject = new JSONObject(result);
    

    You can also use Google's json parse library https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/Gson.html

    Also see this link for details on how to actually parse JSON and get Strings that you can use in your program. How to parse JSON in Android

    0 讨论(0)
  • try

     <?php   echo json_encode($mostra_player, JSON_FORCE_OBJECT); ?> 
    

    which forces to be an object.

    Then you can access it in java/android with

    JSONObject obj = (JSONObject) new JSONTokener(json_string_output).nextValue();
    String yourdata= obj.getString("yourdata");
    

    If you want an Array try

    <?php echo json_encode(array("data" => $mostra_player)); ?>
    
            JSONObject json = new JSONObject(responsedata);
            JSONArray jArray = json.getJSONArray("posts");
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject e = jArray.getJSONObject(i);
                JSONObject jObject = new JSONObject(e.getString("data"));
    
                Log.d("yourdata", jObject.getString("yourdata"));
                Log.d("moredata", jObject.getString("moredata"));
            }
    
    0 讨论(0)
提交回复
热议问题