Converting JSON data to Java object
I want to be able to access properties from a JSON string within my Java action method. The string is available by simply saying myJsonString = object.getJson() . Below is an example of what the string can look like:
In this string every JSON object contains an array of other JSON objects. The intention is to extract a list of IDs where any given object possessing a group property that contains other JSON objects. 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?
14 Answers 14
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 = "]" + ">]" + ">"; // 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 Listgroups; public String getTitle() < return title; >public Long getId() < return id; >public Boolean getChildren() < return children; >public List 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 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:
Performant? Have you actually measured it? While GSON has reasonable feature set, I thought performance was sort of weak spot (as per [cowtowncoder.com/blog/archives/2009/09/entry_326.html]) As to example: I thought GSON did not really need setters, and was based on fields. So code could be simplified slightly.
I use it in an android app. It is not the fastest possible solution but it is simple enough to program to justify the lack of performance for the user until now. Maybe in a later version of the app it will be removed for a faster solution.
Wrt speed, if it’s fast enough, it’s fast enough. I just commented on reference to expected good performance. Feature-set wise Jackson handles all the same nesting, layering, generics, so that’s not where speed difference comes from. Having getters and setters does not impact performance in any measurable way (for packages I am aware of), so definitely can have them there.
i have worked with java and json A LOT. Nothing comes close to Jackson, StaxMan is the DADDY. GSon is a nice try but it doesnt get the Cigar:)
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’ve written a fork of Gson which fixes these issues (and avoids all the annotations of the Jackson): github.com/winterstein/flexi-gson
Oddly, the only decent JSON processor mentioned so far has been GSON.
Here are more good choices:
- Jackson (Github) — powerful data binding (JSON to/from POJOs), streaming (ultra fast), tree model (convenient for untyped access)
- Flex-JSON — highly configurable serialization
String json = ". "; ObjectMapper m = new ObjectMapper(); Set products = m.readValue(json, new TypeReference() <>);
Easy and working java code to convert JSONObject to Java Object
Employee.java
import java.util.HashMap; import java.util.Map; import javax.annotation.Generated; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @Generated("org.jsonschema2pojo") @JsonPropertyOrder(< "id", "firstName", "lastName" >) public class Employee < @JsonProperty("id") private Integer id; @JsonProperty("firstName") private String firstName; @JsonProperty("lastName") private String lastName; @JsonIgnore private MapadditionalProperties = new HashMap(); /** * * @return * The id */ @JsonProperty("id") public Integer getId() < return id; >/** * * @param id * The id */ @JsonProperty("id") public void setId(Integer id) < this.id = id; >/** * * @return * The firstName */ @JsonProperty("firstName") public String getFirstName() < return firstName; >/** * * @param firstName * The firstName */ @JsonProperty("firstName") public void setFirstName(String firstName) < this.firstName = firstName; >/** * * @return * The lastName */ @JsonProperty("lastName") public String getLastName() < return lastName; >/** * * @param lastName * The lastName */ @JsonProperty("lastName") public void setLastName(String lastName) < this.lastName = lastName; >@JsonAnyGetter public Map getAdditionalProperties() < return this.additionalProperties; >@JsonAnySetter public void setAdditionalProperty(String name, Object value) < this.additionalProperties.put(name, value); >>
LoadFromJSON.java
import org.codehaus.jettison.json.JSONObject; import com.fasterxml.jackson.databind.ObjectMapper; public class LoadFromJSON < public static void main(String args[]) throws Exception < JSONObject json = new JSONObject(); json.put("id", 2); json.put("firstName", "hello"); json.put("lastName", "world"); byte[] jsonData = json.toString().getBytes(); ObjectMapper mapper = new ObjectMapper(); Employee employee = mapper.readValue(jsonData, Employee.class); System.out.print(employee.getLastName()); >>
If you wan’t to use it in JSP page then code is still the same. The Employee.java class will be same as it is. But the Code written in LoadFromJSON.java will be copied in jsp page with the proper import of every class. Rest there is no change at all.
If, by any change, you are in an application which already uses http://restfb.com/ then you can do:
import com.restfb.json.JsonObject; . JsonObject json = new JsonObject(jsonString); json.get("title");
your solution is shorter and more understandable, why it only receives 3 upvotes? Is there anything wrong?
Depending on the input JSON format(string/file) create a jSONString. Sample Message class object corresponding to JSON can be obtained as below:
Message msgFromJSON = new ObjectMapper().readValue(jSONString, Message.class);