user1677986
user1677986

Reputation: 61

Json parsing in array java

I am new to JSON parsing and I would need your kind help to understand how to parse a JSON object inside an Array.

My JSON structure log is below:

{A:"text",B:"text",C:[{T:"Text",D:{E:"Text",F:{G:"time"}},H:{I:"200"},J:{K:{L:53,M:2.2},N:"Text"},P:{Q:"Time"}}]}

log is my input JSON as above.

JSONObject logJson = (JSONObject) JSONSerializer.toJSON( log );
String a = logJson.getString("A");
String b = logJson.getString("B");

Now question is how do I parse into the Array and get JSONObject. I am using net.sf API.

Upvotes: 1

Views: 214

Answers (2)

Sashi Kant
Sashi Kant

Reputation: 13465

Hope this will help ::

    JSONObject objonthwiseClaimJSON = JSONObject.fromString(strJSONMonthwiseClaim);

    JSONArray objDateWiseClaimJSONArr = objonthwiseClaimJSON.getJSONArray("dateWiseClaimList");

 for(int dtwclaim=0; dtwclaim<objDateWiseClaimJSONArr.length();dtwclaim++)
{
                 JSONObject objDateWiseClaimJSONObject =(JSONObject) objDateWiseClaimJSONArr.get(dtwclaim);
                 String dcnid = (String) objDateWiseClaimJSONObject.get("dcnid");
                 String remark = (String) objDateWiseClaimJSONObject.get("remark");
    }

In your situation ::

JSONObject logJson = (JSONObject) JSONSerializer.toJSON( log );
String a = logJson.getString("A");
String b = logJson.getString("B");
JSONArray c = logJson.getJSONArray("C"); // If C is not an array, just a plain object

for(int i =0;i<c.length();i++)
{
... // 

}

Upvotes: 0

HashtagMarkus
HashtagMarkus

Reputation: 1661

First of all, I think your json format is invalid.

The "key" must stand in " as well e.g. "A":"text"

You can get the "C" Array by using JSONArray jsonArray = logJson.getJSONArray("C");

On the array you can iterate:

for(int i = 0; i < jsonArray.length(); i++)
{
    JSONObject obj = jsonArray.getJSONObject(i);
    ...
}

Upvotes: 1

Related Questions