Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON in J2ME

So, I've been trying for some time to parse this nested JSON string. If this was regular Java, or even php,I'm sure this would have been done long ago. Unfortunately I'm stuck with J2ME on this one. Through some searching I found that there exits a lone JSON parser. This I found through some digging on a similar question. I've tried some work on my own, with an example on another question. However, I'm still having a few difficulties. I will explain now.

This is the JSON string I'm trying to parse:

{"Result":"Success","Code":"200","CustomerInfo":"{\"clientDisplay\":{\"customerId\":429,\"globalCustNum\":\"0012-000000429\",\"displayName\":\"Hugo Daley\",\"parentCustomerDisplayName\":\"G-KINGSTON\",\"branchId\":12,\"branchName\":\"Bangalore_branch1244724101456\",\"externalId\":\"123000890\",\"customerFormedByDisplayName\":\"New User1244724101456\",\"customerActivationDate\":\"2012-06-17\",\"customerLevelId\":1,\"customerStatusId\":3,\"customerStatusName\":\"Active\",\"trainedDate\":null,\"dateOfBirth\":\"1950-10-10\",\"age\":61,\"governmentId\":\"100000090\",\"clientUnderGroup\":true,\"blackListed\":false,\"loanOfficerId\":17,\"loanOfficerName\":\"New User1244724101456\",\"businessActivities\":null,\"handicapped\":null,\"maritalStatus\":null,\"citizenship\":null,\"ethnicity\":null,\"educationLevel\":null,\"povertyStatus\":null,\"numChildren\":null,\"areFamilyDetailsRequired\":false,\"spouseFatherValue\":null,\"spouseFatherName\":null,\"familyDetails\":null},\"customerAccountSummary\":{\"globalAccountNum\":\"001200000001259\",\"nextDueAmount\":\"2128.0\"},\"clientPerformanceHistory\":{\"loanCycleNumber\":0,\"lastLoanAmount\":\"0.0\",\"noOfActiveLoans\":0,\"delinquentPortfolioAmount\":\"0.0\",\"totalSavingsAmount\":\"1750.0\",\"meetingsAttended\":0,\"meetingsMissed\":0,\"loanCycleCounters\":[],\"delinquentPortfolioAmountInvalid\":false},\"address\":{\"displayAddress\":null,\"city\":\"\",\"state\":\"\",\"zip\":\"\",\"country\":\"\",\"phoneNumber\":\"\"},\"recentCustomerNotes\":[{\"commentDate\":\"2012-06-17\",\"comment\":\"appr\",\"personnelName\":\"New User1244724101456\"}],\"customerFlags\":[],\"loanAccountsInUse\":[{\"globalAccountNum\":\"001200000001262\",\"prdOfferingName\":\"Hawker Loan\",\"accountStateId\":3,\"accountStateName\":\"Application Approved\",\"outstandingBalance\":\"15643.0\",\"totalAmountDue\":\"8977.0\"},{\"globalAccountNum\":\"001200000001279\",\"prdOfferingName\":\"Hazina Micro Loan\",\"accountStateId\":2,\"accountStateName\":\"Application Pending Approval\",\"outstandingBalance\":\"6439.0\",\"totalAmountDue\":\"1716.0\"},{\"globalAccountNum\":\"001200000001280\",\"prdOfferingName\":\"Car Finance\",\"accountStateId\":3,\"accountStateName\":\"Application Approved\",\"outstandingBalance\":\"381.5\",\"totalAmountDue\":\"120.0\"}],\"savingsAccountsInUse\":[{\"globalAccountNum\":\"001200000001260\",\"prdOfferingName\":\"Current Account\",\"accountStateId\":16,\"accountStateName\":\"Active\",\"savingsBalance\":\"1750.0\",\"prdOfferingId\":null}],\"customerMeeting\":{\"meetingSchedule\":\"Recur every 1 Week(s) on Monday\",\"meetingPlace\":\"KINGSTON\"},\"activeSurveys\":false,\"customerSurveys\":[],\"closedLoanAccounts\":[{\"globalAccountNum\":\"001200000001261\",\"prdOfferingName\":\"AUTO LOAN-2\",\"accountStateId\":10,\"accountStateName\":\"Cancel\",\"outstandingBalance\":\"2576.0\",\"totalAmountDue\":\"206.0\"}],\"closedSavingsAccounts\":[]}"}

Don't worry this is just sample data, nothing real here.

Now I require the Customers No, Name, Address, and Savings Account balance. This is the code I've used to parse it:

public CustomerInfo(String jsonTxt) {
try {
    JSONObject json = new JSONObject(jsonTxt);
        JSONObject customer = json.getJSONObject("CustomerInfo");
    custNo = json.getString("globalCustNum");
    custName = json.getString("displayName");
    address = json.getString("DisplayAddress");
    savAcctBal =  json.getDouble("totalSavingsAmount");
} catch (final JSONException je) {
        je.printStackTrace();
}
}

This of course throws an JSONException. I've learned that the JSON Library may have a few bugs. I've done some tricks, with print statements. It turns out that it likes to consume the 1st element of the JSON string. This heavily screws up going through nested elements like we have here in the example.

Is there an alternative I can use?

like image 751
Marc Byfield Avatar asked Oct 08 '22 00:10

Marc Byfield


1 Answers

Boy, do I want to shoot myself. I figured out my issue before I went to bed. My approach was correct; it was just a matter of me reading the output of Print statements wrong as well as underestimated just how nested the JSON was.

Internally, the JSONOBject class stores the JSON elements, pairs, etc. in a Hashtable. The Hashtable has a side-effect where it will sort the data that's given to it. This of course through off how the JSON was ordered. I figured it was consuming some parts of the JSON, while it really was just putting them to the back...the waaay back if not the end of the JSON. This greatly through me off. I did not realise this until I just ran toString on the Hashtable itself. I then also realise that the JSON was actually more nested than I thought. The four parts I wanted to get, where in 3 different nested JSON objects.

Thus, my solution was to save myself even more grief and just put the JSON through a pretty printer and looked and the structure properly.

Here is my Solution code:

 public CustomerInfo(String jsonTxt) {
try {
    JSONObject json = new JSONObject(jsonTxt);
        JSONObject customer = new JSONObject(json.getString("CustomerInfo"));
        JSONObject client = new JSONObject(customer.getString("clientDisplay"));
        custNo = client.getString("globalCustNum");
    custName = client.getString("displayName");
        JSONObject cph = new JSONObject(customer.getString("clientPerformanceHistory"));
        JSONObject caddress = new JSONObject(customer.getString("address"));
    address = caddress.getString("displayAddress");
    savAcctBal =  cph.getDouble("totalSavingsAmount");
} catch (final JSONException je) {
        je.printStackTrace();
}
}

protip: Always use a Pretty Printer on your JSON, and appreciate it's structure before you do anything. I swear this wont happen to me again.

like image 51
Marc Byfield Avatar answered Oct 13 '22 12:10

Marc Byfield