Home > Net >  Json to provide class name path
Json to provide class name path

Time:08-17

When I used org.json version 20090211 I would have Java pojo:

class Person {
   private String name;
   private int age;

   //getters and setters


}

Using json I would put in main:

 JSONObject jsonObject = new JSONObject(person, true);
   System.out.println(jsonObject.toString());

the output:

   {"name":"John","age":30,"class":"class com.Person"}

I need to update this library. With the updated library it only has:

  JSONObject jsonObject = new JSONObject(person);  //without true

Now the output is:

  {"name":"John","age":30}

I am missing the class field. How can I get this field back?

CodePudding user response:

You could e. g. create your JSONObjects by

new JSONObject(person).put("class", Person.class)

Perhaps, you could use a factory method like

public static JSONObject newJSONObject(Object pojo) {
    return new JSONObject(pojo).put("class", pojo.getClass());
}

And, of course, you can modify the library itself.

  • Related