VisioN VisioN - 2 months ago 11
Java Question

How to serialize object to JSON string using classes from "org.json" package?

I've tried to find any useful example to solve this easy task, however, nothing really helpful was found. I'm at the beginner level in Java and I definitely need some help.

I have two simple Java classes:

private class FMList {
public List<FMItem> items = new ArrayList();
public long size = 0;
public int dirs = 0;
public int files = 0;
public String path = "";
}

private class FMItem {
public boolean is_dir = false;
public String[] ascii = {};
public String name = "";
public String mode = "";
public long size = 0;
public long mtime = 0;
public boolean ext = false;
public String cache = "";
}


My application (applet) creates an instance of
FMList
, sets data to object properties, and finally serializes the object to JSON string.

First, I tried Google Gson library. Simple
new Gson().toJson(fmList)
did the job perfectly, however my applet failed to start giving exceptions that Gson library has somewhat like security problems. Meanwhile, the applet was signed and all AccessController's were set.

Then, I tried to use classes from JSON official website. There are no exceptions anymore but that simple
new JSONObject(fmList).toString()
gives
{}
only. I understand that it should be used somehow in a different way.

What is the right way to serialize this simple object to JSON string using classes from
"org.json"
package?


Thank you for help!

Answer

For field access like you are using (not get/set methods) you have to specify them: http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject(java.lang.Object, java.lang.String[])

You either use the JSON Writer or "Stringer" (write to stream or create String) to not get a pretty printed json.

http://www.json.org/javadoc/org/json/JSONWriter.html

http://www.json.org/javadoc/org/json/JSONStringer.html

Update: Also the class can't be private with the simple org.json lib. This works fine:

public class Main {
    public static class FMList {
        public long size = 0;
        public int dirs = 0;
        public int files = 0;
        public String path = "";
    }

    public static void main(String[] args) {
        System.out.println(new JSONObject(new FMList(), new String[] { "dirs", "files" }).toString());
    }

}

Produces: {"files":0,"dirs":0}

Changing to private class produces: {}

Comments