0

I want to expand all variables in a class, then convert them to json string. For example:

class A {
   int a1;
   double a2;
   public A(int a1, double a2) {
      this.a1 = a1;
      this.a2 = a2;
   }
}
class B {
   string b1;
   A a;
   public B(A a, string b1) {
      this.a = a;
      this.b1 = b1;
   }
}

now I have B-class object.

B b = new B(new A(1, 2.5), "test");

Finally, I want to convert B to JSON, but it's not a normal JSON, I want to expand all variables

like this:

{
  "a1": 1,
  "a2": 2.5,
  "b1": "test"
}

not below one

{
  "a": {"a1": 1, "a2": 2.5},
  "b1": "test"
}

I use Jackson, how to realize it in a general way. I think I can put all elements into a map, then finally writeValueAsString, but seems not elegant

loveyzhou
  • 53
  • 7

1 Answers1

0

Use reflection. You can get an array of declared fields in a class, then (via recursion) you can create JSON data from them.

Object o=yourobject;
for(Field field : o.getClass().getFields()) {
        String name=field.getName();
        Class<?> type=field.getType();
        Object value=field.get(o);//you can recursively parse 'value' as well
}

Then you can just use the primivive fields' values directly in json.

A useful post about reflection: What is reflection and why is it useful?