Creating JSON objects directly from model classes in Java

java object to json
convert list of objects to json java jackson
jsonobject java 8
jsonobject to java object
how to create json request in java
jsonobject example
convert string array to json object in java
json stringify java

I have some model classes like Customer, Product, etc. in my project which have several fields and their setter-getter methods, I need to exchange objects of these classes as a JSONObject via Sockets to and from client and server.

Is there any way I can create JSONObject directly from the object of model class such that fields of the object become keys and values of that model class object become values for this JSONObject.

Example:

Customer c = new Customer();
c.setName("Foo Bar");
c.setCity("Atlantis");
.....
/* More such setters and corresponding getters when I need the values */
.....

And I create JSON Object as:

JSONObject jsonc = new JSONObject(c); //I'll use this only once I'm done setting all values.

Which gets me something like:

{"name":"Foo Bar","city":"Atlantis"...}

Please note that, in some of my model classes, certain properties are itself an object of other model class. Such as:

Product p = new Product();
p.setName("FooBar Cookies");
p.setProductType("Food");
c.setBoughtProduct(p);

In a case like above, as I'd expect, the yielded JSON object would be:

{"name":"Foo Bar","city":"Atlantis","bought":{"productname":"FooBar Cookies","producttype":"food"}}

I know I could create something like toJSONString() in each model class and have the JSON-friendly string created and manipulate it then, but in my previous experiences of creating RESTful service in Java (which is totally out of context for this question), I could return JSON string from the service method by using @Produces(MediaType.APPLICATION_JSON) and have the method returning object of model class. So it produced JSON string, which I could consume at the client end.

I was wondering if it's possible to get similar behavior in current scenario.

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());

How to create Json Object using Object Model?, import javax.json.Json;. import javax.json.JsonObject;. import javax.json. JsonObjectBuilder;. import javax.json.JsonWriter;. public class CreateJsonObjEx {. Analyze the JSON object structure and map out your Java classes Manually create each Java class by painstakingly typing each private property name and datatype to match the JSON properties for all

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);

How to create a Java Object from a JSON object, This will be a very brief guide to creating a Java object from a JSON I have a class in my test directory called SimplePojoTest and this is the outline of the class as follows; package com.jtjo.model;import com.google.gson. The object model API is similar to the Document Object Model (DOM) API for XML. It is a high-level API that provides immutable object models for JSON object and array structures. These JSON structures are represented as object models using the Java types JsonObject and JsonArray. Table 1 lists the main classes and interfaces in the object model

    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();
    }

Introduction to JSON-Java, Creating JSON Directly from JSONObject To get a JSONObject from a Java Object, we'll have to use a class that is a valid Java Bean:� Generate Java Class from JSON. Use this tool to quickly generate model classes for Java or POJOs from a sample JSON document. The Java model classes are annotated using JsonProperty attribute supplied by Jackson. JSON. JavaScript Object Notation (JSON) pronounced as "Jason" is the de facto standard for data interchange on the web these days. It

Use gson to achieve this. You can use following code to get the json then

Gson gson = new Gson();
String json = gson.toJson(yourObject);

Convert Java into JSON and JSON into Java. All Possible Examples , How to create a JSON object in Java; How to create JSON object from a JSON String; How to fromJson(arrayFromString, ArrayList.class);. On decoding, the default concrete class of java.util.List is org.json.simple.JSONArray and the default concrete class of java.util.Map is org.json.simple.JSONObject. Encoding JSON in Java. Following is a simple example to encode a JSON object using Java JSONObject which is a subclass of java.util.HashMap. No ordering is provided.

I have used XStream Parser to

    Product p = new Product();
    p.setName("FooBar Cookies");
    p.setProductType("Food");
    c.setBoughtProduct(p);

    XStream xstream = new XStream(new JettisonMappedXmlDriver());
    xstream.setMode(XStream.NO_REFERENCES);
    xstream.alias("p", Product.class);
    String jSONMsg=xstream.toXML(product);
    System.out.println(xstream.toXML(product));

Which will give you JSON string array.

Convert Java Object to Json String using Jackson API , The steps to do this are as follows: Add jar files of Jackson (in case of Maven project add Jackson dependencies in pom.xml file) Create a POJO (Plain Old Java Object) to be converted into JSON. Create a Java class for converting the Organisation object into JSON. Execute the process. Learning how to convert Java objects into JSON and JSON into Java will help you a lot in your work as a full stack mobile app developer. In this blog post I will share with you code examples which will help you do most of the tasks you will even need to do when working with JSON and Java.

How to Convert a Java Object into a JSON String, Objects are created from templates known as classes. An object is an instance of a class. For example, our “Cat object” has:States – color, name� The simplest MVC Java example I could think of; I wanted the MVC version of "Hello World!". Hence sort method cannot be used directly to sort the array. Learn to use jackson objectmapper to populate java object from json string and write json string from java object. json file from template entry. We can just index in using the property name.

Java JSON Example, Java JSON Example. javax.json, JsonObject, Java JSON Parser, JSON Array Object Model API – It's similar to DOM Parser and good for small objects. Json: This is the factory class for creating JSON processing objects. The implementation is straight forward and feels similar as getting parameters from HashMap. Folks who've worked with me know I'm not always a fan of having data-model classes - in a lot of modern web applications you're just taking data from a database, turning it into java objects and turning those into JSON, and applying an access control rule or two - which means the data model is logic-free, so creating it is a waste of time and

JSON with Java, This chapter covers how to encode and decode JSON objects using Java programming language. JSONArray and the default concrete class of java.util. Map is�

Comments
  • I'm relying on JSONObject from json.org library, so do I have to use another library just for this?
  • GSON can do both encoding and decoding, so you can drop json.org and just use GSON instead.
  • Also, I used @XMLElement(name="somekeyname") in get methods of model classes in my REST service thing to control keynames, will it work here too?
  • I don't think so, no. GSON has it's own mechanism for customizing the encoding.
  • The question is about getting Json Object not Json String. So this code need more line about how to convert the string returned from Gson into proper JsonObject
  • Please add some explanation. Your answer is currently flagged "low quality" and might eventually be removed.
  • the OP was asking about JSONObject