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...
}
Answer from Emanuel on Stack Overflowjava - How to get elements of JSONObject? - Stack Overflow
Creating JSON objects directly from model classes in Java - Stack Overflow
Converting JSON data to Java object - Stack Overflow
Is it common that it's so difficult to handle JSON payloads in Java?
Videos
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.
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);
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?