Creating JSON objects directly from model classes in Java
Asked Answered
R

6

33

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.

Romeu answered 7/6, 2012 at 11:10 Comment(0)
C
39

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());
Cornish answered 7/6, 2012 at 11:20 Comment(5)
I'm relying on JSONObject from json.org library, so do I have to use another library just for this?Romeu
GSON can do both encoding and decoding, so you can drop json.org and just use GSON instead.Cornish
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?Romeu
I don't think so, no. GSON has it's own mechanism for customizing the encoding.Cornish
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 JsonObjectHorsa
S
21

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);
Sunwise answered 7/6, 2012 at 11:20 Comment(0)
H
4
    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();
    }
Horsa answered 9/3, 2016 at 8:12 Comment(1)
Please add some explanation. Your answer is currently flagged "low quality" and might eventually be removed.Melchior
P
2

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

Gson gson = new Gson();
String json = gson.toJson(yourObject);
Pilar answered 7/6, 2012 at 11:22 Comment(1)
the OP was asking about JSONObjectStepfather
H
0

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.

Hallucination answered 7/6, 2012 at 11:50 Comment(0)
D
0

if you dont like to use gson you can try with:

ObjectMapper().writeValueAsString(yourObject)

or

String.format("{"email":"%s", emailPassingVariable}")

this will give you {"email":"passingVariableValue"}

Descriptive answered 16/7 at 18:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.