简体   繁体   中英

UPDATED: How can I Insert a Json object inside a Json Array to SQLite

Good day, How to fetch this Json Response and insert it in Android SQLite. Hope you will guide me how to fetch this Json object inside a Json Array inside a Object

{
  "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"
    }
  ]
}

This my whole JSON response. the 1st Json Object(user) was successfully parse and inserted to database but the 2nd Json response(sl_summ) was unsuccessfully parse and was not inserted. and thats my problem.

{  
  "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"
    }
  ]
}

This is the Logcat message

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"}]}
07-05 16:19:15.068 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/ViewRootImpl@dd06ab4[LoginActivity]: dispatchDetachedFromWindow
07-05 16:19:15.083 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/InputTransport: Input channel destroyed: fd=76
07-05 16:19:15.084 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal 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"}}
07-05 16:19:15.085 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/TEST: -error attribute             : false
07-05 16:19:15.094 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SessionManager: User login session modified!
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal 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"}
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -br_code         : 12
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -mem_id          : 13
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -username        : novalyn
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -email           : gsac_tabaco@yahoo.com
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -created at      : 2016-07-22 09:05:21
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: New member was inserted into table members: 13
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: BR CODE: 12
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: Member ID: 13
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: Username: novalyn
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: Email: gsac_tabaco@yahoo.com
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: Created at: 2016-07-22 09:05:21
07-05 16:19:15.118 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal 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"}}
07-05 16:19:15.118 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/sl_summ: -error attribute             : false
07-05 16:19:15.119 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/TEST: org.json.JSONException: No value for sl_summ

I noticed that only the 1st response was returned

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

Here is sample code to convert json string into a json object and access json array and its attributes.

Depending on your table schema in SQLite, you can either insert individual values in columns or persist complete JSON string, it depends on your requirements.

As you have 2 different json strings being processed and if you do not know which one is coming first then you can always check whether the JSONObject user or JSONArray sl_summ is present or not and depending on that you can handle them as follows. Note this is most crude of doing it, i have updated code just to get you going and there are many other way of checking.

import android.util.Log;

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

public static void jsonExample() {
    String loginString = "{\"error\":false, \"user\":{\"br_code\":12,\"mem_id\":13,\"username\":\"test\",\"email\":\"test@yahoo.com\",\"created_at\":\"2016-07-22 09:05:21\"}}";
    String jsonString = "{\"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\" } ] }";
    try {
        Log.d("TEST", "INPUT String                 : " + jsonString);
        JSONObject accountJSONObject = new JSONObject(jsonString);
        displaySubAttributes(accountJSONObject);
        Log.d("TEST", "INPUT String                 : " + loginString);
        JSONObject loginJSONObject = new JSONObject(loginString);
        displaySubAttributes(loginJSONObject);
    } catch (Exception exception) {
        Log.d("TEST", exception.toString());
    }
}

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

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

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

    // Check if its login data i.e. user present
    if (!jsonObject.isNull("user") && slArray == null) {
        // handle user login data
        JSONObject userJSONObject = (JSONObject) jsonObject.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 && jsonObject.isNull("user")) {
        // handle account data
        JSONArray array = ((JSONArray)jsonObject.getJSONArray("sl_summ"));
        // access individual json array thru jsonObject.getJSONArray("FIELD_NAME")
        Log.d("TEST", "-sl_summ array               : " + jsonObject.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());
    }
}

Sample Logs

07-05 16:04:13.352 15643-15643/com.testing.test D/TEST: INPUT String                 : {"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 16:04:13.352 15643-15643/com.testing.test D/TEST: JSON String                  : {"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 16:04:13.352 15643-15643/com.testing.test D/TEST: -error attribute             : false
07-05 16:04:13.352 15643-15643/com.testing.test 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 16:04:13.352 15643-15643/com.testing.test D/TEST: -sl_desc attribute           : PA : Savings Account
07-05 16:04:13.352 15643-15643/com.testing.test D/TEST: -tr_date attribute           : 2015-08-17
07-05 16:04:13.352 15643-15643/com.testing.test D/TEST: -actual_balance attribute    : 483.67
07-05 16:04:13.352 15643-15643/com.testing.test D/TEST: -available_balance attribute : 483.67
07-05 16:04:13.352 15643-15643/com.testing.test D/TEST: ---------------------------------
07-05 16:04:13.352 15643-15643/com.testing.test D/TEST: -sl_desc attribute           : PA : Savings - Cash Bond
07-05 16:04:13.352 15643-15643/com.testing.test D/TEST: -tr_date attribute           : 2015-08-28
07-05 16:04:13.352 15643-15643/com.testing.test D/TEST: -actual_balance attribute    : 10129.43
07-05 16:04:13.352 15643-15643/com.testing.test D/TEST: -available_balance attribute : 10129.43
07-05 16:04:13.352 15643-15643/com.testing.test D/TEST: ---------------------------------

07-05 16:04:13.352 15643-15643/com.testing.test D/TEST: INPUT String                 : {"error":false, "user":{"br_code":12,"mem_id":13,"username":"test","email":"test@yahoo.com","created_at":"2016-07-22 09:05:21"}}
07-05 16:04:13.353 15643-15643/com.testing.test D/TEST: JSON String                  : {"error":false,"user":{"br_code":12,"mem_id":13,"username":"test","email":"test@yahoo.com","created_at":"2016-07-22 09:05:21"}}
07-05 16:04:13.353 15643-15643/com.testing.test D/TEST: -error attribute             : false
07-05 16:04:13.353 15643-15643/com.testing.test D/TEST: User                         : {"br_code":12,"mem_id":13,"username":"test","email":"test@yahoo.com","created_at":"2016-07-22 09:05:21"}
07-05 16:04:13.353 15643-15643/com.testing.test D/TEST: -br_code attribute           : 12
07-05 16:04:13.353 15643-15643/com.testing.test D/TEST: -mem_id attribute            : 13
07-05 16:04:13.353 15643-15643/com.testing.test D/TEST: -username attribute          : test
07-05 16:04:13.353 15643-15643/com.testing.test D/TEST: -email attribute             : test@yahoo.com
07-05 16:04:13.353 15643-15643/com.testing.test D/TEST: -created_at attribute        : 2016-07-22 09:05:21

Here are the steps you can follow:

JSONObject jsonObject = new JSONObject("Your JSON String here");

String error=jsonObject.getString("");

JSONArray s1_sum = jsonObject.getJSONArray("sl_summ");

int s1_sum_length = s1_sum.length();

for (int i = 0; i < s1_sum_length; i++) {
String individualString = statementtag.getJSONObject(i);
sl_desc = individualString.getString("sl_desc");
tr_date = individualString.getString("tr_date");
actual_balance = individualString.getString("actual_balance");
available_balance = individualString.getString("available_balance");

//YOU CAN WRITE INSERT QUERY HERE
}

Here the parsing is called(Passing the response)

getParsing(response.body().string());

Parsing method is here

public void getParsing(String jsonresponse) {


        try {
            JSONArray responseArray = new JSONArray(jsonresponse);
            for (int i = 0; i < responseArray.length(); i++) {
                JSONObject responseObject = responseArray.getJSONObject(i);
                String mId = responseArray.optString("KEY_TAG to get value ID");
                String mName = responseArray.optString("KEY_TAG to get value Name");
                .
                .

                loginDataBaseAdapter = loginDataBaseAdapter.open();
                loginDataBaseAdapter.insertRole(mId, mName);

                loginDataBaseAdapter.close();

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

And your insert query be like

public void insertRole(String id, String name) {
        String selectQuery = "SELECT  * FROM " + DATABASE_ROLES + " WHERE id = '" + name + "'";
        db = dbHelper.getWritableDatabase();

        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor.getCount() > 0) {
            ContentValues newValues = new ContentValues();
            // Assign values for each row.
            newValues.put("id", id);
            newValues.put("name", name);

            int rowsUpdated = db.update(DATABASE_ROLES, newValues, "id= '" + id+ "'", null);
            Log.v("resultState", "resultState==" + rowsUpdated);

        } else {
            ContentValues newValues = new ContentValues();
            // Assign values for each row.
            newValues.put("id", id);
            newValues.put("name", name);

            long result = db.insert(DATABASE_ROLES, null, newValues);
            Log.v("resultState", "resultState==" + result);

        }
        cursor.close();

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM