[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now


Java, JSON and reflection

Posted on 2008-10-09
Medium Priority
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 com.xxx.test.Test with modifiers ""
        at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:65)
LVL 10

Author Comment

ID: 22676562
that is my problem ;)

But you serialize a class, Where is the secret?
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.


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 2000 total points
ID: 22676748

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Suggested Courses

649 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