Gson does not work correctly with JSONObject

My problem is very simple. I have a java object

public class Cat {
   String id;
   String name;
   JSONObject ability;
   // getter and setter
}

and a piece of code

Cat cat = new Cat();
JSONObject ability = new JSONObject();
ability.put("catch", "mouse");
cat.setId("one");
cat.setName("Tom");
cat.setAbility(ability);
System.out.println(new JSONObject(new Gson().toJson(cat)));

and here is output:

{“name”:”Tom”,”id”:”one”,”ability”:{“map”:{“catch”:”mouse”}}}

Can anyone tell me why “map” come up?

Answer

Use com.google.gson.JsonObject instead of org.json.JSONObject

Leave a Reply

Your email address will not be published. Required fields are marked *