1

I have to generate JSON in below sample format:

    [
    {   "roleName" : "Parent Folder", "folderId" : "role1", "expanded" : true, 
        "children" : 
                    [                                                                                                     
                      { "roleName" : "subUser1 non-openable folder", "folderId" : "role11","fileicon" : true },
                      { "roleName" : "subUser2", "folderId" : "role12", "expanded" : true, 
            "children" : 
                       [        
                          { "roleName" : "subUser2-1", "folderId" : "role121", "expanded" : true, "children" : 
                           [
                            { "roleName" : "subUser2-1-1 folder ico", "folderId" : "role1211" },
                            { "roleName" : "subUser2-1-2 file ico", "folderId" : "role1212" , "fileicon" : true}
                           ]
                          }
                      ]
                      }
                    ]
    }
 ]

I have created POJO for same and was able to add array elements in, but unable to add one more array inside or below the element. Please suggest.

below are the pojo I am using.

public class TargetFolder
{
    private TargetChildren[] children;

    private String roleName;

    private String expanded;

    private Long folderId;

    public TargetFolder(String roleName,
            String isFolder, Long folderId, TargetChildren[] folderList) {
        super();
        this.roleName = roleName;
        this.expanded = isFolder;
        this.folderId = folderId;
        this.children = folderList;
    }



    public TargetChildren[] getChildren ()
    {
        return children;
    }

    public void setChildren (TargetChildren[] children)
    {
        this.children = children;
    }

    public String getRoleName ()
    {
        return roleName;
    }

    public void setRoleName (String roleName)
    {
        this.roleName = roleName;
    }

    public String getExpanded ()
    {
        return expanded;
    }

    public void setExpanded (String expanded)
    {
        this.expanded = expanded;
    }

    public Long getFolderId ()
    {
        return folderId;
    }

    public void setFolderId (Long folderId)
    {
        this.folderId = folderId;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [children = "+children+", roleName = "+roleName+", expanded = "+expanded+", folderId = "+folderId+"]";
    }
}

and

public class TargetChildren
{


    private String fileicon;

    private String roleName;

    private long folderId;


    public TargetChildren(String roleName, String fileicon, long folderId) {
        super();
        this.fileicon = fileicon;
        this.roleName = roleName;
        this.folderId = folderId;
    }


    public String getFileicon ()
    {
        return fileicon;
    }

    public void setFileicon (String fileicon)
    {
        this.fileicon = fileicon;
    }

    public String getRoleName ()
    {
        return roleName;
    }

    public void setRoleName (String roleName)
    {
        this.roleName = roleName;
    }

    public long getFolderId ()
    {
        return folderId;
    }

    public void setFolderId (long folderId)
    {
        this.folderId = folderId;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [fileicon = "+fileicon+", roleName = "+roleName+", folderId = "+folderId+"]";
    }
}

and below is the logic I am using to generate the JSON:

for(int i  = 0; i<folderList.size();i++)
        {
            if(folderList!=null)
            {
                subList  = (List)folderList.get(i);
                childFolders[i] = new TargetChildren((String)subList.get(0),(String)subList.get(2),(Long)subList.get(1));
                JSONArray arr =  new JSONArray();
                if(((String)subList.get(2)).equals("true"))
                {
                    arr.put(i, childFolders[i]);
                }
                System.out.println(arr.toString());
                //TargetChildren [] testArr = new TargetChildren[] { new TargetChildren("Folder", "folderName", 226886843L)};
            }
        }
        TargetFolder targetFolder = new TargetFolder(parentFoldername,isFolder,folderId, childFolders);
        JSONObject jsonObject = new JSONObject(targetFolder);
        String jsonString = jsonObject.toString();
        System.out.println("JSON TO UI------ "+jsonString);
8
  • 1
    You have a malformed JSON. Please put the proper JSON you are trying to parse. Commented Jul 20, 2015 at 14:14
  • 1
    Your JSON is not valid. keys must be surrounded by quotes + Your array doesn't have a key - should be something like: "arr": [{...},{...}....]. Commented Jul 20, 2015 at 14:47
  • Yes, I know it's not proper json, will post it for sure but my main concern here is adding a complete array inside existing array.. Commented Jul 20, 2015 at 14:58
  • @Codebender,ItayD I have added corrct JSON, please suggest. Commented Jul 21, 2015 at 4:54
  • Show us your POJO and how you are trying to add elements Commented Jul 21, 2015 at 5:03

1 Answer 1

1

The most elegant and simple solution I can think of is adding a toJSON method to your POJOs and let it handle the serializing itself.

For the TargetFolder:

public JSONObject toJSON(){
    JSONObject out = new JSONObject();
    out.put("rolename", rolename);
    out.put("expanded", expanded);
    out.put("folderID", folderId);

    JSONArray children = new JSONArray();
    for(int i = 0; i < this.children.length; i++){
        children.push(this.children[i].toJSON());
    }
    out.put("children", children);

    return out;
}

Do the same for the TargetChildren and then you can convert it to JSON by calling:

myTargetFolder.toJSON();

This way you don't need to worry about the recursive structure of the resulting JSON.

If you add a constructor which takes a JSONObject, you can ensure consistent serialization and deserialization in one place.

There is also the GSON library from Google, which should achieve essentially the same, but I never used it, so I cannot say how it would work with that.


P.S.: You might want to create a common superclass for TargetFolder and TargetChild and use that as the datatype for the children-array, because from the JSON it seems like this array can contain objects with TargetFolder-properties ("expanded" and "children") and objects with TargetChild-properties ("fileicon")

Sign up to request clarification or add additional context in comments.

7 Comments

I am confused. Do u want me to add toJSON() in my both POJO? and where exactly I can call the myTargetFolder.toJSON();
Yes, add that method (with a meaningful implementation) to both POJOs. You can call that method anywhere, where you want to convert the POJO to JSON.
thanks for your effort, it worked for me but partially :) I have added below method in my TargetChild and method given by you in TargetFolder: JSONArray children = new JSONArray(); for(int i = 0; i < 2; i++){ children.put(out.toString); without children.put(out.toString) it throws Exception in thread "main" java.lang.StackOverflowError at org.json.JSONObject.keySet(JSONObject.java:730). and using children.put(out.toString) add some extra stuff in my JSON.
@nilFi I'm sorry, I can't understand your problem. Where exactly did you add that code?
@nilFi out is only supposed to be a representation of this (TargetChild). From your question I see, that TargetChild only has the attributes roleName, fileIcon and fileID, so only these attributes should be in the JSONObject which is produced by the toJSON-method. If you put out into the JSONObject out, you create an infinite loop. It is the same as saying: this.attribute = this. I hope this helps.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.