Java, JSON and reflection

Posted on 2008-10-09
Last Modified: 2013-12-22
Hy all

I playing a little with Java and Reflection.

So the Idea is to transform a Java object in a JSON object.

For now seems that works if I have a class just with public fields. But if I have package fields, they aren't collectable like this. How to get them?

Note: I will say thanks if you get me a Lib doing this, but I prefer to do it myself.

package oleber.json.simple;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Map;
public class JSONable implements IJSONable {
	public JSONObject toJSON() {
		try {
			JSONObject objJSON = new JSONObject();
			JSONObject objValues = new JSONObject();
			JSONObject objTypes = new JSONObject();
			objJSON.put("values", objValues);
			objJSON.put("types", objTypes);
			for ( Field field : getClass().getFields() ) {
				if ( field.getType() == byte.class ) {
					objValues.put(field.getName(), field.getByte(this));
				} else if ( field.getType() == char.class ) {
					objValues.put(field.getName(), field.getChar(this));
				} else if ( field.getType() == short.class ) {
					objValues.put(field.getName(), field.getShort(this));
				} else if ( field.getType() == int.class ) {
					objValues.put(field.getName(), field.getInt(this));
				} else if ( field.getType() == long.class ) {
					objValues.put(field.getName(), field.getLong(this));
				} else if ( field.getType() == float.class ) {
					objValues.put(field.getName(), field.getFloat(this));
				} else if ( field.getType() == double.class ) {
					objValues.put(field.getName(), field.getDouble(this));
				} else if ( field.getType() == boolean.class ) {
					objValues.put(field.getName(), field.getBoolean(this));
				} else if ( field.getType() == String.class ) {
					objValues.put(field.getName(), field.get(this));
				} else {
					Object value = field.get(this);
					if ( value == null ) {
						objValues.put(field.getName(), null);
					} else if ( value instanceof String || value instanceof IJSONable) {
						objValues.put(field.getName(), value);
						objTypes.put(field.getName(), value.getClass().toString());
					} else if ( value instanceof Collection ) {
						JSONArray array = new JSONArray( ( Collection<?> ) value );
						objValues.put(field.getName(), array);
						objTypes.put(field.getName(), value.getClass().toString());
					} else if ( value instanceof Map ) {
						JSONObject object = new JSONObject( ( Map<String,?> ) value );
						objValues.put(field.getName(), object);
						objTypes.put(field.getName(), value.getClass().toString());
			return objJSON;
		} catch ( Exception e ) {
			return null;
	public JSONable toJSON(JSONObject obj) {
		return null;
	public String toString() {
		return toJSON().toString();

Open in new window

Question by:oleber
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 2

Expert Comment

ID: 22676503
Try the following. This will return an array of all fields of the class, including package, private, protected and public fields.
for ( Field field : getClass().getDeclaredFields() ) {

Open in new window


Expert Comment

ID: 22676527
hmm. ignore it. with this code snippet you get the fields but you can't access them from another package.
With field.isAccessible() you can check the accessibility of the field. If this field has default access only, you will get an error:
java.lang.IllegalAccessException: Class reflectiontest.Main can not access a member of class with modifiers ""
        at sun.reflect.Reflection.ensureMemberAccess(
LVL 10

Author Comment

ID: 22676562
that is my problem ;)

But you serialize a class, Where is the secret?
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.


Expert Comment

ID: 22676639
Do you know the structure of the classes?

Can't you access the package variables from the get methods?
LVL 10

Author Comment

ID: 22676690
I'm trying to do this generic. Basically every child class from this would be able of convert itself to JSON.

Expert Comment

ID: 22676735

Accepted Solution

manuel_m earned 500 total points
ID: 22676748

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Suggested Courses

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question