Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a JSON representation of a Java class?

Tags:

java

json

class

Id like to represent a Class object as JSON. For example, if I have the class defintions as follows:

public class MyClass {
    String myName;
    int myAge;
    MyOtherClass other;
}

public class MyOtherClass {
    double myDouble;
}

I'd like to get the following nested JSON from a Class object of type MyClass:

{
   myName: String,
   myAge: int,
   other: {
      myDouble: double;
   }
}

EDIT:

I don't want to serialize instances of these classes, I understand how to do that with GSON. I want to serialize the structure of the class itself, so that given a proprietary class Object I can generate JSON that breaks down the fields of the class recursively into standard objects like String, Double, etc.

like image 696
Sam Stern Avatar asked Jun 19 '12 18:06

Sam Stern


2 Answers

With Jettison, you can roll your own mappings from Java to JSON. So in this case, you could get the Class object of the class you want, then map the Java returned by the getFields, getConstructors, getMethods etc. methods to JSON using Jettison.

like image 155
smcg Avatar answered Oct 18 '22 10:10

smcg


I would recommend to use Jackson. You can also take a look at the JSonObjectSerializer class based on Jackson which can be found at oVirt under engine/backend/manager/module/utils (you can git clone the code) and see how we used Jackson there.

like image 35
Yair Zaslavsky Avatar answered Oct 18 '22 09:10

Yair Zaslavsky