Solved

Java, JSON and reflection

Posted on 2008-10-09
7
1,623 Views
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 {
 

	@Override

	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 ) {

			e.printStackTrace();

			return null;

		}

	}
 

	@Override

	public JSONable toJSON(JSONObject obj) {

		return null;

	}
 

	@Override

	public String toString() {

		return toJSON().toString();

	}

}

Open in new window

0
Comment
Question by:oleber
  • 5
  • 2
7 Comments
 
LVL 6

Expert Comment

by:manuel_m
Comment Utility
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

0
 
LVL 6

Expert Comment

by:manuel_m
Comment Utility
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)
0
 
LVL 10

Author Comment

by:oleber
Comment Utility
that is my problem ;)


But you serialize a class, Where is the secret?
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 6

Expert Comment

by:manuel_m
Comment Utility
Do you know the structure of the classes?

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

Author Comment

by:oleber
Comment Utility
I'm trying to do this generic. Basically every child class from this would be able of convert itself to JSON.
0
 
LVL 6

Expert Comment

by:manuel_m
Comment Utility
0
 
LVL 6

Accepted Solution

by:
manuel_m earned 500 total points
Comment Utility
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
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…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

743 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now