如何获取两个Json响应Json Object和Array [英] How to fetch two Json response Json Object and Array

查看:135
本文介绍了如何获取两个Json响应Json Object和Array的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取这两个Json响应并将json响应保存在SQLite中.希望您能指导我如何在对象内部的Json数组中获取此Json对象

How to fetch this Two Json Response and save the json response in SQLite. Hope you will guide me how to fetch this Json object inside a Json Array inside an Object

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

My problem is a cannot fetch the 2nd json response. I noticed that only the 1st response was returned

Logcat中的登录响应

Login response in 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仅返回第一个响应

only the 1st response was returned in this 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中

This is the 1st Json response. Was parse and stored in 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

This is the 2nd Json response. Json object inside a JSON Array. Was not parse and inserted in 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

This is my 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

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

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

推荐答案

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

NOTE: as mentioned in previous question, the given JSON string needs to be in correct format i.e. either have a key for each object (login, accounts) or have them in a single array (input). I am giving solution for both the options.

新手,我为您提供2个单独的方法,以便您可以根据传入JSON字符串的构造方式(单个JSON字符串中的2个对象或JSON数组中的2个对象)来处理传入的JSON字符串.

Novice, I am providing you 2 separate methods so that you can handle incoming JSON string depending on how you construct it either 2 objects in single JSON String or 2 objects in an JSON array.

您可以选择解决方案:)

You can pick your solution :)

尝试代码,如果需要更多帮助,请告诉我.

Try the code, let me know if you need more help and accept the answer.

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

OPTION1 : 2 Objects in single 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"
         }
      ]
   }
}

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

OPTION2 : 2 Objects in single JSON array 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"
            }
         ]
      }
   ]
}

用于处理JSON字符串的两种情况(OPTION1和OPTION2)的代码

Code to handle both the scenarios (OPTION1 & OPTION2) of JSON String

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&的样本日志选项2

Sample Logs for OPTION1 & OPTION2

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对象的代码.

I do not have access to all the internal PHP files which i can use to run your PHP Code, so I replaced most of all the function calls with hard coded values as shared in sample response payload. Here is the code to generate JSON Objects in OPTION1 format.

简而言之,您必须在$ response中的所有子属性之前添加["login"]和["accounts"],以便将它们分组在正确的JSON对象中,并且您将拥有两个可以与上面的android共享代码一起解析.

In short, you have to add ["login"] and ["accounts"] ahead of all the sub attributes in $response so that they will be grouped in correct JSON Object and you will have two JSON objects that can be parsed with above android shared code.

<?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)

PHP Sample Run generated JSON response (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 上提供几天.

Code will be available for few days at https://codepad.remoteinterview.io/YJJKVUEAAH

这篇关于如何获取两个Json响应Json Object和Array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆