wangzewei
wangzewei

Reputation: 35

How do I convert a Java Bean to a JsonObject?

I know that a JsonObject in the package org.json could create a JsonObject with a constructor whose argument is an object, but I could't find it in Eclipse.

As the image shows

After adding the org.json dependency, below is how it's showing up.

Upvotes: 1

Views: 3053

Answers (2)

Thusitha Indunil
Thusitha Indunil

Reputation: 832

You can used following method for convert your java bean object into JSON Object. I have added few data type, Also used common format to add into json object. You can customize wish to want. You just want to pass Object reference to this method.

private JSONObject beanToJSON(Object bean) {
    JSONObject json = new JSONObject();

    try {
        Field[] fields = bean.getClass().getDeclaredFields();
        System.out.println(fields.length);

        for (Field f : fields) {
            String field = f.getName();
            Class params[] = {};
            Object paramsObj[] = {};

            Method method = bean.getClass().getDeclaredMethod("get" + StringUtils.capitalise(field), params);
            Object v = method.invoke(bean, paramsObj);

            Class t = f.getType();

            if (t == boolean.class && Boolean.FALSE.equals(v)) {
                json.accumulate(field, v.toString());

            } else if (t.isPrimitive() && ((Number) v).doubleValue() == 0) {
                json.accumulate(field, v.toString());

            } else if (t.isPrimitive() && ((Number) v).intValue() == 0) {
                json.accumulate(field, v.toString());

            } else if (t == String.class) {
                json.accumulate(field, v.toString());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return json;
}

Upvotes: 0

Madhu Bhat
Madhu Bhat

Reputation: 15193

The reason you are not able to see that constructor is since the JSONObject class that you are using is from the android-json package. You can see the same constructors in the Android JSONObject doc.

To get the JSONObject that you're expecting, you would need to add the dependency of org.json as below (either Maven or Gradle)

Maven dependency

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20180813</version>
</dependency>

Gradle dependency

compile group: 'org.json', name: 'json', version: '20180813'

Then import this JSONObject class and you would see the constructor that you actually want.

Upvotes: 1

Related Questions