Creating JSON objects directly from model classes in Java Creating JSON objects directly from model classes in Java json json

Creating JSON objects directly from model classes in Java


Google GSON does this; I've used it on several projects and it's simple and works well. It can do the translation for simple objects with no intervention, but there's a mechanism for customizing the translation (in both directions,) as well.

Gson g = ...;String jsonString = g.toJson(new Customer());


You can use Gson for that:

Maven dependency:

<dependency>    <groupId>com.google.code.gson</groupId>    <artifactId>gson</artifactId>    <version>2.8.0</version></dependency>

Java code:

Customer customer = new Customer();Product product = new Product();// Set your values ...Gson gson = new Gson();String json = gson.toJson(customer);Customer deserialized = gson.fromJson(json, Customer.class);


    User = new User();    Gson gson = new Gson();    String jsonString = gson.toJson(user);    try {        JSONObject request = new JSONObject(jsonString);    } catch (JSONException e) {        // TODO Auto-generated catch block        e.printStackTrace();    }