2

I have the following String which is returning from the Database in the form of List, My assumption is that, the list contains 3 items. but it is showing only "1" as the size. So it is returning all the activity items as one element.

Note: When I try to get the first index of the list (list.get(0)), it returns only one "activity" not all the three(as a single item).I don't know what is happening inside the list.

My Question: How to convert the below list of strings which contains 1 item(with 3 activity items) into List which should consider list size as 3(3 activity).

[ { "activity" : { "id" : "a_3" , "kind" : "Infomation" , "userId" : 100 , "accountId" : 0 , "timestamp" : 1476369009366 , "result" : "normal"  }} ,
 { "activity" : { "id" : "a_18" , "kind" : "Infomation" , "userId" : 100 , "accountId" : 0 ,"timestamp" : 1476419696003 , "result" : "normal" }} , 
 { "activity" : { "id" : "a_4" , "kind" : "Infomation" , "userId" : 100, "accountId" : 0 , ""timestamp" : 1476435910335 , "result" : "normal" }}]

The above information is from the DB:

Iterable<DBObject> results =null;
List<String> retList = new ArrayList<>();
        try {
            results= collection.aggregate(pipeline).results();
        } catch (Exception e) {
        }
        if(results!=null){
            Iterator<DBObject> iterator = results.iterator();
            while (iterator.hasNext()) { 
                String input = iterator.next().get("actLogList").toString();
                retList.add(input.substring(input.indexOf("[") + 1, input.lastIndexOf("]")));
            }
        }
        return retList;
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
M.S.Naidu
  • 2,239
  • 5
  • 32
  • 56

2 Answers2

1

1.) create json array by passing your string to constructor

2.) traverse array and retrieve your jsonObject using index i

3.) fetch the activity jsonobject and then simply use your index to fetch the values for jsonActivityItem object.

4.) create a POJO class to store your object in a collection like List etc but make sure to mark them private and use getter and setters for best practice

class User{
    String id,kind,result;
    int userId,accountId;
    long timestamp;
    //.. getter & setters 
}

Note : To convert your string to json compatible you can use JsonParser , try this link JsonParser snippet

    JSONArray array;
    List<User> listUser=new ArrayList<>(); // to store objects as details
    try {
        array=new JSONArray(st); // st is your string ( make sure to use jsonparser )
        JSONObject jsonActivity;
        JSONObject jsonActivityItem;
        User user;
        for (int i=0;i<array.length();i++) {
            System.out.println();
            jsonActivity=array.getJSONObject(i);
            jsonActivityItem=jsonActivity.getJSONObject("activity");                

            // To store data for later use
            user = new User();
            user.setId(jsonActivityItem.getString("id"));
            user.settimestamp(jsonActivityItem.getLong("timestamp"));
            //..set other values using setters 
            listUser.add(user);

            // to display items

            String id        = jsonActivityItem.optString("id");
            String kind      = jsonActivityItem.optString("kind");
            String userId    = jsonActivityItem.optString("userId");
            String accountId = jsonActivityItem.optString("accountId");
            String timestamp = jsonActivityItem.optString("timestamp");
            String result    = jsonActivityItem.optString("result");
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

I would recommend an easy and short way i.e using gson to convert it into list but you will required to use POJO class you can take a look at this link to create a compatible POJO class and later just use Gson code

Nullity check : Sometime you may see some exceptions when the values are not available so in those cases when you are not sure about the presence of value so use optInt optBoolean etc which will simply return the default value if it is not present and even try to convert value to int if it is string like

from docs

Get an optional int value associated with a key, or the default if there is no such key or if the value is not a number. If the value is a string, an attempt will be made to evaluate it as a number.

int block_id = jObj.getInt("key",defaultvalue);

e.g

int block_id = jObj.getInt("userId",0); 
Community
  • 1
  • 1
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
  • if you have the control over this DB output then i would recommend to make your `activity` index a single array , containing all other objects it will be more efficient in this way, instead of 3 objects containing single -2 object – Pavneet_Singh Oct 15 '16 at 11:46
0

You have to use GSON library to parse this JSON array. You need to do something similar to below code.

    JSONArray jsonArray = new JSONArray(jsonArrayString);
    List<String> list = new ArrayList<String>();
    for (int i=0; i<jsonArray.length(); i++) {
        list.add( jsonArray.getString(i) );
    }
Ganesh S
  • 510
  • 11
  • 19