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());
Answer from Ernest Friedman-Hill on Stack OverflowCreating JSON objects directly from model classes in Java - Stack Overflow
java - How to get elements of JSONObject? - Stack Overflow
java - Use JSON objects or POJOs in back end service? - Software Engineering Stack Exchange
Converting JSON data to Java object - Stack Overflow
Videos
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);
JSONObject json = new JSONObject(yourdata);
String statistics = json.getString("statistics");
JSONObject name1 = json.getJSONObject("John");
String ageJohn = name1.getString("Age");
For getting those items in a dynamic way:
JSONObject json = new JSONObject(yourdata);
String statistics = json.getString("statistics");
for (Iterator key=json.keys();key.hasNext();) {
JSONObject name = json.get(key.next());
//now name contains the firstname, and so on...
}
You did not specify which library you intend to use to represent the JSON object. Usually there are methods to enumerate the properties of the object. For example:
org.json.JSONObject.keys()
returns an iterator of the String names in the object.
It's usually a good idea to separate the serialization method (JSON) from your business logic so that if in the future you decide to use some other type of serialization, you can do so without affecting the business logic.
Jackson is probably the most popular open-source library for JSON serialization/deserialization in Java.
In the situation where some amount of transformation is needed between the data received from your customer database and what you actually return to the caller, I usually create a separate DTO (data-transfer object) class that contains only the fields to be serialized.
On the other hand, if you always need to remove the same fields from the customer data before transmittal and don't mind putting serialization-specific annotations on your POJOs, you can use Jackson's @JsonIgnore (or similar) on those fields and skip the DTO.
I'd go for the simplest and easiest solution which will cover your current requirement.
As you mentioned all you need is to remove couple of fields, json manipulation is enough and it's very simple.
In future, as you believe if it comes to more complex transformations (which are not easy to do with json manipulation) you can easily add DTOs in middle and do the transformations. Since you are getting json and sending back json adding DTOs won't affect any of the external systems.
I looked at Google's Gson as a potential JSON plugin. Can anyone offer some form of guidance as to how I can generate Java from this JSON string?
Google Gson supports generics and nested beans. The [] in JSON represents an array and should map to a Java collection such as List or just a plain Java array. The {} in JSON represents an object and should map to a Java Map or just some JavaBean class.
You have a JSON object with several properties of which the groups property represents an array of nested objects of the very same type. This can be parsed with Gson the following way:
package com.stackoverflow.q1688099;
import java.util.List;
import com.google.gson.Gson;
public class Test {
public static void main(String... args) throws Exception {
String json =
"{"
+ "'title': 'Computing and Information systems',"
+ "'id' : 1,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Level one CIS',"
+ "'id' : 2,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Intro To Computing and Internet',"
+ "'id' : 3,"
+ "'children': 'false',"
+ "'groups':[]"
+ "}]"
+ "}]"
+ "}";
// Now do the magic.
Data data = new Gson().fromJson(json, Data.class);
// Show it.
System.out.println(data);
}
}
class Data {
private String title;
private Long id;
private Boolean children;
private List<Data> groups;
public String getTitle() { return title; }
public Long getId() { return id; }
public Boolean getChildren() { return children; }
public List<Data> getGroups() { return groups; }
public void setTitle(String title) { this.title = title; }
public void setId(Long id) { this.id = id; }
public void setChildren(Boolean children) { this.children = children; }
public void setGroups(List<Data> groups) { this.groups = groups; }
public String toString() {
return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
}
}
Fairly simple, isn't it? Just have a suitable JavaBean and call Gson#fromJson().
See also:
- Json.org - Introduction to JSON
- Gson User Guide - Introduction to Gson
Bewaaaaare of Gson! It's very cool, very great, but the second you want to do anything other than simple objects, you could easily need to start building your own serializers (which isn't that hard).
Also, if you have an array of Objects, and you deserialize some json into that array of Objects, the true types are LOST! The full objects won't even be copied! Use XStream.. Which, if using the jsondriver and setting the proper settings, will encode ugly types into the actual json, so that you don't loose anything. A small price to pay (ugly json) for true serialization.
Note that Jackson fixes these issues, and is faster than GSON.
I'm trying to learn and use Java with spring boot to rewrite a service in the current system. The existing service is heavily written in Node and has so many payloads passed between many services in JSON format. Rewriting it now feels so painful.
In Node, handling these JSON format is a breeze. But now that I'm using Java, I'm having a nightmare handling them. I'm using Jackson but I just find myself having to create so many object classes just to handle these JSON payloads. And some of these payloads are often deeply nested and have complicated data, which means I will have write a number of custom serlializers and deserializers.
I have also found that those annotations make these class files (or POJOs) somewhat coupled to the JSON payloads because of the annotations. Whenever another service makes a change to the payload such as changing its fields, I will have even more to change!
After handling the JSON objects, occasionally, I've to further convert them into another type of object which will require mapstructs which is again another hell of annotations and configurations to figure out.
I feel like I'm spending so much time just on the payloads even before I can start on the actual biz logic.
Is it common to be so painful when handling JSON in Java? Or am I missing out something that could have made my life a lot easier?