How to make a JSON representation of a Java class?

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

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

public class MyOtherClass {
    double myDouble;
}

I would like to get the following nested JSON from a class object of type MyClass:

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

EDIT:

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

+5
source share
3 answers

. JSonObjectSerializer Jackson, oVirt /backend/manager/module/utils ( git ) , .

+1

Jettison Java JSON. , , Java, getFields, getConstructors, getMethods .. JSON, Jettison.

+3

, , , , . - , , :

@Override
public Map reflectModelAsMap(Class classType) {
    List<Class> mappedTracker = new LinkedList<Class>();

    return reflectModelAsMap(classType, mappedTracker);
}

private Map reflectModelAsMap(Class classType, List mappedTracker) {
    Map<String, Object> mapModel = new LinkedHashMap<String, Object>();

    mappedTracker.add(classType);

    Field[] fields = classType.getDeclaredFields();

    for (Field field : fields) {
        if (mappedTracker.contains(field.getType()))
            continue;

        if (BeanUtils.isSimpleValueType(field.getType())) {
            mapModel.put(field.getName(), field.getType().toString());
        } else if (Collection.class.isAssignableFrom(field.getType())) {
            Class actualType = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
            mapModel.put("Collection", reflectModelAsMap(actualType, mappedTracker));
        } else {
            mapModel.put(field.getName(), reflectModelAsMap(field.getType(), mappedTracker));
        }
    }

    return mapModel;
}

- , Hibernate; , . child.getFather().getFirstChild().getFather().getFirstChild().getFather()...

0
source

All Articles