如何获取两个Json响应Json Object和Array

时间:2017-07-05 08:48:25

标签: android json android-sqlite

如何获取此两个Json Response并在SQLite中保存json响应。希望您能指导我如何在Object

中的Json数组中获取此Json对象

我的问题是无法获取第二个json响应。我注意到只返回了第一个回复

Logcat中的登录响应

D/RegisterActivity: Login Response: {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}{"error":false,"sl_summ":[{"sl_desc":"PA : Savings Account","tr_date":"2015-08-17","actual_balance":"483.67","available_balance":"483.67"},{"sl_desc":"PA : Savings - Cash Bond","tr_date":"2015-08-28","actual_balance":"10129.43","available_balance":"10129.43"}]}

此Logcat中仅返回第一个响应

D/sl_summ: JSON String : {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
D/sl_summ: -error attribute: false
D/TEST: org.json.JSONException: No value for sl_summ

这是第一个Json回应。解析并存储在SQLite中

{  
  "error": false,
  "user": {
    "br_code": 12,
    "mem_id": 13,
    "username": "novalyn",
    "email": "gsac_tabaco@yahoo.com",
    "created_at": "2016-07-22 09:05:21"
  }
}

这是第二个Json回复。 JSON数组中的Json对象。没有解析并插入SQLite

{
  "error": false,
  "sl_summ": 
  [
    {
      "sl_desc": "PA : Savings Account",
      "tr_date": "2015-08-17",
      "actual_balance": "483.67",
      "available_balance": "483.67"
    },
    {
      "sl_desc": "PA : Savings - Cash Bond",
      "tr_date": "2015-08-28",
      "actual_balance": "10129.43",
      "available_balance": "10129.43"
    }
  ]
}

整个JSON响应

{  
  "error": false,
  "user": {
    "br_code": 12,
    "mem_id": 13,
    "username": "novalyn",
    "email": "gsac_tabaco@yahoo.com",
    "created_at": "2016-07-22 09:05:21"
  }
}
{
  "error": false,
  "sl_summ": 
  [
    {
      "sl_desc": "PA : Savings Account",
      "tr_date": "2015-08-17",
      "actual_balance": "483.67",
      "available_balance": "483.67"
    },
    {
      "sl_desc": "PA : Savings - Cash Bond",
      "tr_date": "2015-08-28",
      "actual_balance": "10129.43",
      "available_balance": "10129.43"
    }
  ]
}

这是我的Login.java

try {
    JSONObject jObj = new JSONObject(response.toString());
    boolean error = jObj.getBoolean("error");
    Log.d(TAG, "Checking JSON Object" +jObj);

    Log.d("TEST", "-error attribute             : " + jObj.get("error").toString());
    // Check for error node in json
    if (!error) {
        // user successfully logged in
        // Create login session
        session.setLogin(true);

        // Now store the user in SQLite
        //String uid = jObj.getString("uid");

        JSONObject user = jObj.getJSONObject("user");
            Log.d("USER", "-user object     : " + jObj.getJSONObject("user").toString());
        String br_code = user.getString("br_code");
            Log.d("USER", "-br_code         : " + br_code);
        String mem_id = user.getString("mem_id");
            Log.d("USER", "-mem_id          : " + mem_id);
        String username = user.getString("username");
            Log.d("USER", "-username        : " + username);
        String email = user.getString("email");
            Log.d("USER", "-email           : " + email);
        String created_at = user.getString("created_at");
            Log.d("USER", "-created at      : " + created_at);

        // Inserting row in users table
        db.addUser(br_code, mem_id, username, email, created_at);

        //SL Details
        try {
            // read the json string into a json object
            JSONObject jsonObject = new JSONObject(response.toString());
            Log.d("sl_summ", "JSON String                  : " + jsonObject.toString());
            // access individual json object thru jsonObject.get("FIELD_NAME")
            Log.d("sl_summ", "-error attribute             : " + jsonObject.get("error").toString());
            // access individual json array thru jsonObject.getJSONArray("FIELD_NAME")
            Log.d("sl_summ", "-sl_summ array               : " + jsonObject.getJSONArray("sl_summ").toString());
            JSONArray array = ((JSONArray)jsonObject.getJSONArray("sl_summ"));
            for (int index=0; index<array.length(); index++) {
                JSONObject object = (JSONObject)array.get(index);
                Log.d("SL_SUUM", "-sl_desc attribute           : " + object.get("sl_desc").toString());
                Log.d("SL_SUUM", "-tr_date attribute           : " + object.get("tr_date").toString());
                Log.d("SL_SUUM", "-actual_balance attribute    : " + object.get("actual_balance").toString());
                Log.d("SL_SUUM", "-available_balance attribute : " + object.get("available_balance").toString());
                Log.d("SL_SUUM", "---------------------------------");
            }
        } catch (Exception exception) {
            Log.d("TEST", exception.toString());
        }

        // Launch main activity
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    } else {
        // Error in login. Get the error message
        String errorMsg = jObj.getString("error_msg");
        Toast.makeText(getApplicationContext(),
                errorMsg, Toast.LENGTH_LONG).show();
    }
} catch (JSONException e) {
    // JSON error
    e.printStackTrace();
    Log.d("TEST", e.toString());
    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}

SQlitehandler.java

public void addUserSLDTL(String sl_desc, String tr_date, String  actual_balance, String avail_balance){
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(SL_DESC, sl_desc); // sl desc
    values.put(TR_DATE, tr_date); // trans date
    values.put(ACTUAL_BALANCE, actual_balance); // actual balance
    values.put(AVAILABLE_BALANCE, avail_balance); // availabe balance

    // Inserting Row
    long id = db.insertOrThrow(TABLE_MEMBERS_SLDTL, null, values);
    db.close(); // Closing database connection

    Log.d(TAG, "Members's SL Details was inserted into sldtl table: " + id);
    Log.d(TAG, "SL Desc: " + sl_desc);
    Log.d(TAG, "Transaction Date: " + tr_date);
    Log.d(TAG, "Actual Balance: " + actual_balance);
    Log.d(TAG, "Available Balance: " + avail_balance);
}

public HashMap<String, String> getUserSLDTL() {
    HashMap<String, String> sl_summ = new HashMap<String, String>();
    String selectQuery = "SELECT * FROM " + TABLE_MEMBERS_SLDTL;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // Move to first row
    cursor.moveToFirst();
    if (cursor.getCount() > 0) {
        sl_summ.put("sl_desc", cursor.getString(0));
        sl_summ.put("tr_date", cursor.getString(1));
        sl_summ.put("actual_balance", cursor.getString(2));
        sl_summ.put("avail_balance", cursor.getString(3));

        Log.d(TAG, "member's SLDTL data: " + sl_summ.toString());
    }
    else{
        Log.d(TAG, "member's SLDTL data is empty");
    }
    cursor.close();
    db.close();

    // return user
    Log.d(TAG, "Fetching member's SL details from Sqlite sldtl table: " + sl_summ.toString());

    return sl_summ;
}

Logcat消息

D/RegisterActivity: Login Response: {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}{"error":false,"sl_summ":[{"sl_desc":"PA : Savings Account","tr_date":"2015-08-17","actual_balance":"483.67","available_balance":"483.67"},{"sl_desc":"PA : Savings - Cash Bond","tr_date":"2015-08-28","actual_balance":"10129.43","available_balance":"10129.43"}]}
D/ViewRootImpl@dd06ab4[LoginActivity]: dispatchDetachedFromWindow
D/InputTransport: Input channel destroyed: fd=76
D/RegisterActivity: Checking JSON Object{"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
D/TEST: -error attribute             : false
D/SessionManager: User login session modified!
D/USER: -user object     : {"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}
D/USER: -br_code         : 12
D/USER: -mem_id          : 13
D/USER: -username        : novalyn
D/USER: -email           : gsac_tabaco@yahoo.com
D/USER: -created at      : 2016-07-22 09:05:21
D/SQLiteHandler: New member was inserted into table members: 13
D/SQLiteHandler: BR CODE: 12
D/SQLiteHandler: Member ID: 13
D/SQLiteHandler: Username: novalyn
D/SQLiteHandler: Email: gsac_tabaco@yahoo.com
D/SQLiteHandler: Created at: 2016-07-22 09:05:21
D/sl_summ: JSON String                  : {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
D/sl_summ: -error attribute             : false
D/TEST: org.json.JSONException: No value for sl_summ

的login.php

<?php
session_start();
require_once 'include/DB_Functions.php';
$db = new DB_Functions();

// json response array
$response = array("error" => FALSE);
$br_response = array("error" => FALSE);
$sl_response["error"] = FALSE;
$sl_response["sl_summ"] = array();

$arclass = "13";
$loanclass = "12";
$accintreceivable = "21";

if (isset($_POST['username']) && isset($_POST['password'])) {

    // receiving the post params
    $username= $_POST['username'];
    $password = $_POST['password'];

    // get the user by username and password
    $user = $db->getUserByUsernameAndPassword($username, $password);

    if ($user != null) {
        // user is found
        $response["error"] = FALSE;
        $response["user"]["br_code"] = $user["MEMBER_ID_BRCODE"];
        $response["user"]["mem_id"] = $user["MEMBER_ID"];
        $response["user"]["username"] = $user["USERNAME"];
        $response["user"]["email"] = $user["EMAIL"];
        $response["user"]["created_at"] = $user["REG_DATE"];
        json_encode($response, true);
        //Displaying json value
        echo json_encode($response, true);

        //$_SESSION= json_encode($response, true);
        // $_SESSION['br_code']= $user["MEMBER_ID_BRCODE"];
        // $_SESSION['username']= $user["USERNAME"];
        // $_SESSION['mem_id']= $user["MEMBER_ID"];

        $br_code= $user["MEMBER_ID_BRCODE"];
        $clientid= $user["MEMBER_ID"];
        //Check if the branch of the user exist in the BRANCH table
        $user = $db->getBrnchInfo($br_code);
        //var_dump($user);
        if ($user != null) {
            $br_response["error"] = FALSE;
            $br_response["user_br"]["ar_class"] = $arclass;
            $br_response["user_br"]["loan_class"] = $loanclass;
            $br_response["user_br"]["accnt_receivable"] = $accintreceivable;
            $br_response["user_br"]["br_code"] = $user["br_id"];
            $br_response["user_br"]["br_desc"] = $user["br_desc"];
            $br_response["user_br"]["br_address"] = $user["br_add"];
            $br_response["user_br"]["br_manager"] = $user["br_manager"];
            $br_response["user_br"]["br_accronym"] = $user["br_accronym"];
            $br_response["user_br"]["br_trans_date"] = $user["br_trans_date"];
            //json_encode($br_response, true);
            //echo json_encode($br_response, true);

            $trans_date = strtotime($user["br_trans_date"]);
            $date  = date('d',$trans_date);
            $year  = date('Y',$trans_date);
            $month = date('m',$trans_date);

            $user_sldtl = $db->getUserSLsummary($arclass, $loanclass, $accintreceivable, $date, $year, $month, $br_code, $clientid);

            If($user_sldtl != null) {
                 for($i = 0; $i < count($user_sldtl); $i++){
                    $item = array();
                        $item["sl_desc"] = $user_sldtl[$i][7];
                        $item["tr_date"] = $user_sldtl[$i][10];
                        $item["actual_balance"] = $user_sldtl[$i][14];
                        $item["available_balance"] = $user_sldtl[$i][14];

                        $response = array("error" => FALSE);
                        $sl_response["sl_summ"][] = $item;
                    }
                    json_encode($sl_response);
                    echo json_encode($sl_response, true);
             }
             else {
                 $sl_response["error"] = TRUE;
                 $sl_response["error_msg"] = "NO SL Details found!";
                 echo json_encode($sl_response);
             }
        }
        else {
            $response["error"] = TRUE;
            $response["error_msg"] = "No branch code found.!";
            json_encode($response);
           // echo json_encode($response);
        }

        //header('Location: accountsummary.php');
    } else {
        // user is not found with the credentials
        $response["error"] = TRUE;
        $response["error_msg"] = "Login credentials are wrong. Please try again!";
        json_encode($response);
        echo json_encode($response);
        // echo "<br />" .$username. "<br />";
        // echo $password;
    }
} else {
    // required post params is missing
    $response["error"] = TRUE;
    $response["error_msg"] = "Required parameters username or password is missing!";
    json_encode($response);
    echo json_encode($response);
}
?>

3 个答案:

答案 0 :(得分:0)

// your JSON format is wrong . you should arrange proper json data format 
//Like this:-  
{
  "obj1": {
    "error": false,
    "user": {
      "br_code": 12,
      "mem_id": 13,
      "username": "novalyn",
      "email": "gsac_tabaco@yahoo.com",
      "created_at": "2016-07-22 09:05:21"
    }
  },
  "obj2": {
    "error": false,
    "sl_summ": [
      {
        "sl_desc": "PA : Savings Account",
        "tr_date": "2015-08-17",
        "actual_balance": "483.67",
        "available_balance": "483.67"
      },
      {
        "sl_desc": "PA : Savings - Cash Bond",
        "tr_date": "2015-08-28",
        "actual_balance": "10129.43",
        "available_balance": "10129.43"
      }
    ]
  }
}

答案 1 :(得分:0)

这是Json响应的正确格式:

{
    "object1":{
        "error":false,
            "user":{
        "br_code":12,
                "mem_id":13,
                "username":"novalyn",
                "email":"gsac_tabaco@yahoo.com",
                "created_at":"2016-07-22 09:05:21"
    }
    }
    "object2":{
        "error":false,
            "sl_summ":
        [
        {
            "sl_desc":"PA : Savings Account",
                "tr_date":"2015-08-17",
                "actual_balance":"483.67",
                "available_balance":"483.67"
        },
        {
            "sl_desc":"PA : Savings - Cash Bond",
                "tr_date":"2015-08-28",
                "actual_balance":"10129.43",
                "available_balance":"10129.43"
        }
        ]
    }
}

现在使用以下方法解析您的回复

private void parseJsonResponse(String jsonString)
{
    try
    {
        JSONObject rootJsonObject = new JSONObject(jsonString);
        JSONObject object1 = rootJsonObject.has("object1") ? rootJsonObject.getJSONObject("object1") : new JSONObject();
        JSONObject object2 = rootJsonObject.has("object2") ? rootJsonObject.getJSONObject("object2") : new JSONObject();

       // Now get remaining values from object1 and object2

    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}

答案 2 :(得分:0)

注意:如上一个问题所述,给定的JSON字符串需要格式正确,即每个对象都有一个键(登录,帐户)或将它们放在一个数组中(输入)。我正在为这两个选项提供解决方案。

新手,我为您提供了两种不同的方法,以便您可以处理传入的JSON字符串,具体取决于您如何构造单个JSON字符串中的2个对象或JSON数组中的2个对象。

您可以选择解决方案:)

试试代码,如果您需要更多帮助并接受答案,请告诉我。

OPTION1:单个JSON字符串中的2个对象

{
   "login":{
      "error":false,
      "user":{
         "br_code":12,
         "mem_id":13,
         "username":"novalyn",
         "email":"gsac_tabaco@yahoo.com",
         "created_at":"2016-07-22 09:05:21"
      }
   },
   "accounts":{
      "error":false,
      "sl_summ":[
         {
            "sl_desc":"PA : Savings Account",
            "tr_date":"2015-08-17",
            "actual_balance":"483.67",
            "available_balance":"483.67"
         },
         {
            "sl_desc":"PA : Savings - Cash Bond",
            "tr_date":"2015-08-28",
            "actual_balance":"10129.43",
            "available_balance":"10129.43"
         }
      ]
   }
}

OPTION2:单个JSON数组字符串中的2个对象

{
   "input":[
      {
         "error":false,
         "user":{
            "br_code":12,
            "mem_id":13,
            "username":"novalyn",
            "email":"gsac_tabaco@yahoo.com",
            "created_at":"2016-07-22 09:05:21"
         }
      },
      {
         "error":false,
         "sl_summ":[
            {
               "sl_desc":"PA : Savings Account",
               "tr_date":"2015-08-17",
               "actual_balance":"483.67",
               "available_balance":"483.67"
            },
            {
               "sl_desc":"PA : Savings - Cash Bond",
               "tr_date":"2015-08-28",
               "actual_balance":"10129.43",
               "available_balance":"10129.43"
            }
         ]
      }
   ]
}

用于处理JSON字符串

的场景(OPTION1和OPTION2)的代码
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public static void jsonExample() {
    // OPTION 1
    String twoObjectString = "{ \"login\":{ \"error\":false, \"user\":{ \"br_code\":12, \"mem_id\":13, \"username\":\"novalyn\", \"email\":\"gsac_tabaco@yahoo.com\", \"created_at\":\"2016-07-22 09:05:21\" } }, \"accounts\":{ \"error\":false, \"sl_summ\":[ { \"sl_desc\":\"PA : Savings Account\", \"tr_date\":\"2015-08-17\", \"actual_balance\":\"483.67\", \"available_balance\":\"483.67\" }, { \"sl_desc\":\"PA : Savings - Cash Bond\", \"tr_date\":\"2015-08-28\", \"actual_balance\":\"10129.43\", \"available_balance\":\"10129.43\" } ] } }\n";
    // OPTION 2
    String arrayString = "{ \"input\": [ { \"error\":false, \"user\":{ \"br_code\":12, \"mem_id\":13, \"username\":\"novalyn\", \"email\":\"gsac_tabaco@yahoo.com\", \"created_at\":\"2016-07-22 09:05:21\" } }, { \"error\":false, \"sl_summ\":[ { \"sl_desc\":\"PA : Savings Account\", \"tr_date\":\"2015-08-17\", \"actual_balance\":\"483.67\", \"available_balance\":\"483.67\" }, { \"sl_desc\":\"PA : Savings - Cash Bond\", \"tr_date\":\"2015-08-28\", \"actual_balance\":\"10129.43\", \"available_balance\":\"10129.43\" } ] } ] }\n";
    try {
        Log.d("TEST", "COMBINED 2 OBJECTS             ");
        Log.d("TEST", "INPUT String                 : " + twoObjectString);
        JSONObject twoJSONObjects = new JSONObject(twoObjectString);
        handleTwoObjects(twoJSONObjects);

        Log.d("TEST", "2 OBJECTS IN ARRAY             ");
        Log.d("TEST", "INPUT String                   " + arrayString);
        JSONObject arrayJSONObject = new JSONObject(arrayString);
        handleArrayOfObjects(arrayJSONObject);
    } catch (Exception exception) {
        Log.d("TEST", exception.toString());
    }
}

// OPTION 1
public static void handleTwoObjects(JSONObject jsonObject)  throws Exception {
    // read the json string into a json object
    Log.d("TEST", "JSON String                  : " + jsonObject.toString());

    if (!jsonObject.isNull("login")) {
        JSONObject loginObject = (JSONObject) jsonObject.get("login");

        // access individual json object thru jsonObject.get("FIELD_NAME")
        Log.d("TEST", "-error attribute             : " + loginObject.get("error").toString());

        // Check if its login data i.e. user present
        if (!loginObject.isNull("user")) {
            // handle user login data
            JSONObject userJSONObject = (JSONObject) loginObject.get("user");
            Log.d("TEST", "User                         : " + userJSONObject.toString());
            Log.d("TEST", "-br_code attribute           : " + userJSONObject.get("br_code").toString());
            Log.d("TEST", "-mem_id attribute            : " + userJSONObject.get("mem_id").toString());
            Log.d("TEST", "-username attribute          : " + userJSONObject.get("username").toString());
            Log.d("TEST", "-email attribute             : " + userJSONObject.get("email").toString());
            Log.d("TEST", "-created_at attribute        : " + userJSONObject.get("created_at").toString());
            // Check if its account data i.e. sl_summ is present
        } else {
            // a new JSON string that doesn't have user in login Object
            Log.d("TEST", "Unknown JSON String          : " + loginObject.toString());
        }
    }

    if (!jsonObject.isNull("accounts")) {
        JSONObject accountsObject = (JSONObject) jsonObject.get("accounts");

        // access individual json object thru jsonObject.get("FIELD_NAME")
        Log.d("TEST", "-error attribute             : " + accountsObject.get("error").toString());

        JSONArray slArray = accountsObject.optJSONArray("sl_summ");

        // Check if its login data i.e. user present
        if (slArray != null) {
            // handle account data
            JSONArray array = ((JSONArray)accountsObject.getJSONArray("sl_summ"));
            // access individual json array thru jsonObject.getJSONArray("FIELD_NAME")
            Log.d("TEST", "-sl_summ array               : " + accountsObject.getJSONArray("sl_summ").toString());
            for (int index=0; index<array.length(); index++) {
                JSONObject object = (JSONObject)array.get(index);
                Log.d("TEST", "-sl_desc attribute           : " + object.get("sl_desc").toString());
                Log.d("TEST", "-tr_date attribute           : " + object.get("tr_date").toString());
                Log.d("TEST", "-actual_balance attribute    : " + object.get("actual_balance").toString());
                Log.d("TEST", "-available_balance attribute : " + object.get("available_balance").toString());
                Log.d("TEST", "---------------------------------");
            }
        } else {
            // a new JSON string that doesn't have sl_summ as member variable so display it and write new handler code
            Log.d("TEST", "Unknown JSON String          : " + jsonObject.toString());
        }
    }
}

// OPTION 2
public static void handleArrayOfObjects(JSONObject jsonObject)  throws Exception {
    // read the json string into a json object
    Log.d("TEST", "JSON String                  : " + jsonObject.toString());

    JSONArray inputArray = jsonObject.optJSONArray("input");

    if (inputArray != null && inputArray.length() > 0) {
        for (int oindex = 0; oindex < inputArray.length(); oindex++) {

            JSONObject currentObject = (JSONObject) inputArray.get(oindex);

            JSONArray slArray = currentObject.optJSONArray("sl_summ");

            // access individual json object thru jsonObject.get("FIELD_NAME")
            Log.d("TEST", "-error attribute             : " + currentObject.get("error").toString());

            // Check if its login data i.e. user present
            if (!currentObject.isNull("user") && slArray == null) {
                // handle user login data
                JSONObject userJSONObject = (JSONObject) currentObject.get("user");
                Log.d("TEST", "User                         : " + userJSONObject.toString());
                Log.d("TEST", "-br_code attribute           : " + userJSONObject.get("br_code").toString());
                Log.d("TEST", "-mem_id attribute            : " + userJSONObject.get("mem_id").toString());
                Log.d("TEST", "-username attribute          : " + userJSONObject.get("username").toString());
                Log.d("TEST", "-email attribute             : " + userJSONObject.get("email").toString());
                Log.d("TEST", "-created_at attribute        : " + userJSONObject.get("created_at").toString());
                // Check if its account data i.e. sl_summ is present
            } else if (slArray != null && currentObject.isNull("user")) {
                // handle account data
                JSONArray array = ((JSONArray)currentObject.getJSONArray("sl_summ"));
                // access individual json array thru jsonObject.getJSONArray("FIELD_NAME")
                Log.d("TEST", "-sl_summ array               : " + currentObject.getJSONArray("sl_summ").toString());
                for (int index=0; index<array.length(); index++) {
                    JSONObject object = (JSONObject)array.get(index);
                    Log.d("TEST", "-sl_desc attribute           : " + object.get("sl_desc").toString());
                    Log.d("TEST", "-tr_date attribute           : " + object.get("tr_date").toString());
                    Log.d("TEST", "-actual_balance attribute    : " + object.get("actual_balance").toString());
                    Log.d("TEST", "-available_balance attribute : " + object.get("available_balance").toString());
                    Log.d("TEST", "---------------------------------");
                }
            } else {
                // a new JSON string that doesn't have user or sl_summ as member variable so display it and write new handler code
                Log.d("TEST", "Unknown JSON String          : " + jsonObject.toString());
            }
        }
    }
}

OPTION1&amp;的示例日志选项2

07-05 20:21:58.001 8178-8178/? D/TEST: COMBINED 2 OBJECTS             
07-05 20:21:58.001 8178-8178/? D/TEST: INPUT String                 : { "login":{ "error":false, "user":{ "br_code":12, "mem_id":13, "username":"novalyn", "email":"gsac_tabaco@yahoo.com", "created_at":"2016-07-22 09:05:21" } }, "accounts":{ "error":false, "sl_summ":[ { "sl_desc":"PA : Savings Account", "tr_date":"2015-08-17", "actual_balance":"483.67", "available_balance":"483.67" }, { "sl_desc":"PA : Savings - Cash Bond", "tr_date":"2015-08-28", "actual_balance":"10129.43", "available_balance":"10129.43" } ] } }
07-05 20:21:58.001 8178-8178/? D/TEST: JSON String                  : {"login":{"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}},"accounts":{"error":false,"sl_summ":[{"sl_desc":"PA : Savings Account","tr_date":"2015-08-17","actual_balance":"483.67","available_balance":"483.67"},{"sl_desc":"PA : Savings - Cash Bond","tr_date":"2015-08-28","actual_balance":"10129.43","available_balance":"10129.43"}]}}
07-05 20:21:58.001 8178-8178/? D/TEST: -error attribute             : false
07-05 20:21:58.001 8178-8178/? D/TEST: User                         : {"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}
07-05 20:21:58.001 8178-8178/? D/TEST: -br_code attribute           : 12
07-05 20:21:58.001 8178-8178/? D/TEST: -mem_id attribute            : 13
07-05 20:21:58.001 8178-8178/? D/TEST: -username attribute          : novalyn
07-05 20:21:58.001 8178-8178/? D/TEST: -email attribute             : gsac_tabaco@yahoo.com
07-05 20:21:58.001 8178-8178/? D/TEST: -created_at attribute        : 2016-07-22 09:05:21
07-05 20:21:58.001 8178-8178/? D/TEST: -error attribute             : false
07-05 20:21:58.001 8178-8178/? D/TEST: -sl_summ array               : [{"sl_desc":"PA : Savings Account","tr_date":"2015-08-17","actual_balance":"483.67","available_balance":"483.67"},{"sl_desc":"PA : Savings - Cash Bond","tr_date":"2015-08-28","actual_balance":"10129.43","available_balance":"10129.43"}]
07-05 20:21:58.002 8178-8178/? D/TEST: -sl_desc attribute           : PA : Savings Account
07-05 20:21:58.002 8178-8178/? D/TEST: -tr_date attribute           : 2015-08-17
07-05 20:21:58.002 8178-8178/? D/TEST: -actual_balance attribute    : 483.67
07-05 20:21:58.002 8178-8178/? D/TEST: -available_balance attribute : 483.67
07-05 20:21:58.002 8178-8178/? D/TEST: ---------------------------------
07-05 20:21:58.002 8178-8178/? D/TEST: -sl_desc attribute           : PA : Savings - Cash Bond
07-05 20:21:58.002 8178-8178/? D/TEST: -tr_date attribute           : 2015-08-28
07-05 20:21:58.002 8178-8178/? D/TEST: -actual_balance attribute    : 10129.43
07-05 20:21:58.002 8178-8178/? D/TEST: -available_balance attribute : 10129.43
07-05 20:21:58.002 8178-8178/? D/TEST: ---------------------------------


07-05 20:21:58.002 8178-8178/? D/TEST: 2 OBJECTS IN ARRAY             
07-05 20:21:58.002 8178-8178/? D/TEST: INPUT String                   { "input": [ { "error":false, "user":{ "br_code":12, "mem_id":13, "username":"novalyn", "email":"gsac_tabaco@yahoo.com", "created_at":"2016-07-22 09:05:21" } }, { "error":false, "sl_summ":[ { "sl_desc":"PA : Savings Account", "tr_date":"2015-08-17", "actual_balance":"483.67", "available_balance":"483.67" }, { "sl_desc":"PA : Savings - Cash Bond", "tr_date":"2015-08-28", "actual_balance":"10129.43", "available_balance":"10129.43" } ] } ] }
07-05 20:21:58.002 8178-8178/? D/TEST: JSON String                  : {"input":[{"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}},{"error":false,"sl_summ":[{"sl_desc":"PA : Savings Account","tr_date":"2015-08-17","actual_balance":"483.67","available_balance":"483.67"},{"sl_desc":"PA : Savings - Cash Bond","tr_date":"2015-08-28","actual_balance":"10129.43","available_balance":"10129.43"}]}]}
07-05 20:21:58.002 8178-8178/? D/TEST: -error attribute             : false
07-05 20:21:58.002 8178-8178/? D/TEST: User                         : {"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}
07-05 20:21:58.002 8178-8178/? D/TEST: -br_code attribute           : 12
07-05 20:21:58.002 8178-8178/? D/TEST: -mem_id attribute            : 13
07-05 20:21:58.002 8178-8178/? D/TEST: -username attribute          : novalyn
07-05 20:21:58.002 8178-8178/? D/TEST: -email attribute             : gsac_tabaco@yahoo.com
07-05 20:21:58.002 8178-8178/? D/TEST: -created_at attribute        : 2016-07-22 09:05:21
07-05 20:21:58.002 8178-8178/? D/TEST: -error attribute             : false
07-05 20:21:58.002 8178-8178/? D/TEST: -sl_summ array               : [{"sl_desc":"PA : Savings Account","tr_date":"2015-08-17","actual_balance":"483.67","available_balance":"483.67"},{"sl_desc":"PA : Savings - Cash Bond","tr_date":"2015-08-28","actual_balance":"10129.43","available_balance":"10129.43"}]
07-05 20:21:58.002 8178-8178/? D/TEST: -sl_desc attribute           : PA : Savings Account
07-05 20:21:58.002 8178-8178/? D/TEST: -tr_date attribute           : 2015-08-17
07-05 20:21:58.002 8178-8178/? D/TEST: -actual_balance attribute    : 483.67
07-05 20:21:58.002 8178-8178/? D/TEST: -available_balance attribute : 483.67
07-05 20:21:58.002 8178-8178/? D/TEST: ---------------------------------
07-05 20:21:58.002 8178-8178/? D/TEST: -sl_desc attribute           : PA : Savings - Cash Bond
07-05 20:21:58.002 8178-8178/? D/TEST: -tr_date attribute           : 2015-08-28
07-05 20:21:58.002 8178-8178/? D/TEST: -actual_balance attribute    : 10129.43
07-05 20:21:58.002 8178-8178/? D/TEST: -available_balance attribute : 10129.43
07-05 20:21:58.002 8178-8178/? D/TEST: ---------------------------------

我无法访问可用于运行PHP代码的所有内部PHP文件,因此我将大部分函数调用替换为样本响应有效负载中共享的硬编码值。以下是以OPTION1格式生成JSON对象的代码。

简而言之,您必须在$ response中的所有子属性之前添加[&#34; login&#34;]和[&#34; accounts&#34;],以便将它们分组到正确的JSON对象中并且你将有两个JSON对象可以使用上面的android共享代码进行解析。

<?php
// json response array
$br_response = array("error" => FALSE);
$sl_response["error"] = FALSE;
$sl_response["sl_summ"] = array();

$arclass = "13";
$loanclass = "12";
$accintreceivable = "21";

        // user is found
        $response["login"]["error"] = FALSE;
        $response["login"]["user"]["br_code"] = 12;
        $response["login"]["user"]["mem_id"] = 13;
        $response["login"]["user"]["username"] = "novalyn";
        $response["login"]["user"]["email"] = "gsac_tabaco@yahoo.com";
        $response["login"]["user"]["created_at"] = "2016-07-22 09:05:21";
                 for($i = 0; $i < 2; $i++){
                        $item = array();
                        $item["sl_desc"] = "PA : Savings Account";
                        $item["tr_date"] = "2015-08-17";
                        $item["actual_balance"] = "483.67";
                        $item["available_balance"] = "483.67";
                        $sl_response["sl_summ"][] = $item;
                    }
                    $response["accounts"] = $sl_response;
                    json_encode($response);
                    echo json_encode($response, true);

PHP示例运行生成的JSON响应(OPTION1)

{
   "login":{
      "error":false,
      "user":{
         "br_code":12,
         "mem_id":13,
         "username":"novalyn",
         "email":"gsac_tabaco@yahoo.com",
         "created_at":"2016-07-22 09:05:21"
      }
   },
   "accounts":{
      "error":false,
      "sl_summ":[
         {
            "sl_desc":"PA : Savings Account",
            "tr_date":"2015-08-17",
            "actual_balance":"483.67",
            "available_balance":"483.67"
         },
         {
            "sl_desc":"PA : Savings Account",
            "tr_date":"2015-08-17",
            "actual_balance":"483.67",
            "available_balance":"483.67"
         }
      ]
   }
}

代码将在https://codepad.remoteinterview.io/YJJKVUEAAH

处提供几天