Save object name into a instance variable during GSON Deserialization - json

Suppose I have a json file like this:
{
"ObjectName1": {
"enabled": true,
"SSOIDS": []
},
"ObjectName2": {
"enabled": true,
"SSOIDS": []
},
"ObjectName3": {
"enabled": true,
"SSOIDS": []
},
"ObjectName4": {
"enabled": true,
"IDs": []
}
}
I want to derserialize the data and store the "ObjectNameX" into a field, objectName, of my Java object e.g:
public class Feature implements Serializable {
private static final long serialVersionUID = 1L;
private String objectName;
private Boolean enabled;
private List<String> IDs;
private boolean checkLastTwoChars; //sometimes my json objects might have this
//element.However in this example it doesn't
//Getters and Setters left out for brevity
I have read a bit on creating a custom deserializer here
and have created the below class:
public class FeatureDeserializer implements JsonDeserializer<Feature> {
public Feature deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
Feature ft = new Feature();
if(!json.isJsonNull()){
ft.setFeatureName(json.getAsJsonObject().getAsString());
//json.getAsJsonObject().getAsString()--> `{"enabled":true,"SSOIDS":[],"checkLastTwoChars":false}
}
return ft;
}
}
but the json parameter in the deserializer doesn't have access to the objectNameX during runtime i.e only the key value pairs of the objet fields are available.
I know GSON is deserializing the correct values and has access to the a objectNameX from eclipse debugger.
Here's how I am calling the fromJson():
// just the part I think is relevant
Map<String, Feature> featureCache = new HashMap<String, Feature>();
for(File file : files){
try {
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder sb = new StringBuilder();
while(br.ready()){
sb.append(br.readLine());
}
br.close();
Gson gson = new GsonBuilder().setPrettyPrinting().
registerTypeAdapter(Feature.class, new FeatureDeserializer()).create();
featureCache = gson.fromJson(sb.toString(), new TypeToken<SortedMap<String, Feature>>(){}.getType()); // features in a specific file
Is there a standard way for saving each objectNamex in each unique object that I deserialize??

Here's my solution to the problem of saving each objectNamex in each unique object that I deserialize however I am still unsure if this is a best or even common practice.
I realized that:
Gson gson = new GsonBuilder().setPrettyPrinting().
registerTypeAdapter(Feature.class, new FeatureDeserializer()).create();
featureCache = gson.fromJson(sb.toString(), new TypeToken<SortedMap<String, Feature>>(){}.getType()); // features in a specific file
is actually creating a map with the objectNamex as the key to each unique Feature object therefore
I created a helper function:
private void fillInFeatureNames(Map<String, Feature> featureCache){
for (String featName: featureCache.keySet()){
featureCache.get(featName).setFeatureName(featName);
}
}
that cycles through each key in the map and sets each unique feature object featureName field to the keyname. This is a valid work around but I still wanted to know if there was a preferred practice in this effort.

Related

Render complex object in JSON in grails

I have complex object and I want to render it, but I have several problems in view.
First of all, I have UUID field in my class but in View I get not the String but mostSigBits and leastSigBits.
The second one, I have my enums fields like two fields with enum and value
For example,
public class ExampleObject {
#JsonProperty("id")
private UUID id;
#JsonProperty("name")
private String name;
#JsonProperty("address")
private String address;
#JsonProperty("port")
private String port;
#JsonProperty("users")
#Valid
private List<UserRef> users = null;
#JsonProperty("indexingParameters")
private IndexingParameters indexingParameters;
#JsonProperty("otherParameters")
private OtherParameters otherParameters;
#JsonProperty("status")
private Status status;
}
When I get response from controller I get answer with this one
{
"id": {
"leastSignificantBits": -5406850341911646206,
"mostSignificantBits": 8884977146336383467
},
"status": {
"enumType": "api.model.Status",
"name": "GENERAL"
}
....
}
The problem is I have a lot of different but with the same problem objects in my code. If there is only 1 object, I`d easy prepare some _exampleObject.gson template and render every answer from controller to it, but I have many objects.
I think there are some variants to render correct my JSON, isn`t there?
Another rendering variants where data is ExampleObject.class or something like that
1)code:
Map map = [content: data.content, sorting: data.sorting, paging: data.paging] as Map
render AppResponse.success([success: true, data: map]).asJSON()
render data as JSON
on front:
Incorrect UUID and DateTime convert each field in Object, But I need Timeshtamp
"id": {"leastSignificantBits": -5005002633583312101,
"mostSignificantBits": 4056748206401340307},
"key": "b48d35dd-0551-4265-a1b1-65105e713811",
2)code:
Map map = [data: new ObjectMapper().writeValueAsString(data)] as Map
render map
on front:
Here we can see square brackets at the start which is wrong for JSON
['data':'{"content":[{"id":"384c7700-09c1-4393-ba8a-a89f555f431b","name":"somename"...
3)code:
Object result = new HashMap<String, Object>()
result.success = true
result["data1"] = new ObjectMapper().writeValueAsString(data)
render result as JSON
on front:
Here we can see quotes escaping
"data": "{\"content\":[{\"id\":\"384c7700-09c1-4393-ba8a-a89f555f431b\",\"name\":\"somename\",\"key\":\"b48d35dd-0551-4265-a1b1-65105e713811\",\"status\":\"COMPLETED\.......
I did it like this
#CompileStatic
class MyProxyController {
#Autowired
Myservice service
static ObjectMapper objectMapper = new ObjectMapper()
.registerModule(new JodaModule())
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
def getExampleObject {
ExampleObject exampleObject = service.getExampleObject()
render([contentType: "application/json"], objectMapper.writeValueAsString(new CustomObject(data, true)))
}
#CompileStatic
class CustomObject {
Boolean success
Object data
CustomObject(Object data, Boolean success) {
this.data = data
this.success = success
}
}
}
And get json as I wanted like
{
"success": true,
"data": {
"content": [
{ ....

How to solve circular reference when serializing an object which have a class member with the same type of that object

I'm facing this issue when using Gson to serialize an object which has a class member with the same type:
https://github.com/google/gson/issues/1447
The object:
public class StructId implements Serializable {
private static final long serialVersionUID = 1L;
public String Name;
public StructType Type;
public StructId ParentId;
public StructId ChildId;
And since StructId contains ParentId/ChildId with the same type I was getting infinite loop when trying to serialize it, so what I did is:
private Gson gson = new GsonBuilder()
.setExclusionStrategies(new ExclusionStrategy() {
public boolean shouldSkipClass(Class<?> clazz) {
return false; //(clazz == StructId.class);
}
/**
* Custom field exclusion goes here
*/
public boolean shouldSkipField(FieldAttributes f) {
//Ignore inner StructIds to solve circular serialization
return ( f.getName().equals("ParentId") || f.getName().equals("ChildId") );
}
})
/**
* Use serializeNulls method if you want To serialize null values
* By default, Gson does not serialize null values
*/
.serializeNulls()
.create();
But this is not good enough cause I need the data inside Parent/Child and ignoring them while serializing is not a solution.
How is it possible to solve it?
Related to the answer marked as Solution:
I have such a struct:
- Struct1
-- Table
--- Variable1
The object before serialization is:
And Json that is generated is:
As you can see, the ParentId of Table is "Struct1" but the ChildId of "Struct1" is empty and it should be "Table"
B.R.
I think using ExclusionStrategy is not the right approach to solve this problem.
I would rather suggest to use JsonSerializer and JsonDeserializer
customized for your StructId class.
(May be an approach using TypeAdapter would be even better,
but I didn't have enough Gson experience do get this working.)
So you would create your Gson instance by:
Gson gson = new GsonBuilder()
.registerTypeAdapter(StructId.class, new StructIdSerializer())
.registerTypeAdapter(StructId.class, new StructIdDeserializer())
.setPrettyPrinting()
.create();
The StructIdSerializer class below is responsible for converting a StructId to JSON.
It converts its properties Name, Type and ChildId to JSON.
Note that it does not convert the property ParentId to JSON,
because doing that would produce infinite recursion.
public class StructIdSerializer implements JsonSerializer<StructId> {
#Override
public JsonElement serialize(StructId src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("Name", src.Name);
jsonObject.add("Type", context.serialize(src.Type));
jsonObject.add("ChildId", context.serialize(src.ChildId)); // recursion!
return jsonObject;
}
}
The StructIdDeserializer class below is responsible for converting JSON to a StructId.
It converts the JSON properties Name, Type and ChildId
to corresponding Java fields in StructId.
Note that the ParentId Java field is reconstructed from the JSON nesting structure,
because it is not directly contained as a JSON property.
public class StructIdDeserializer implements JsonDeserializer<StructId> {
#Override
public StructId deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
StructId id = new StructId();
id.Name = json.getAsJsonObject().get("Name").getAsString();
id.Type = context.deserialize(json.getAsJsonObject().get("Type"), StructType.class);
JsonElement childJson = json.getAsJsonObject().get("ChildId");
if (childJson != null) {
id.ChildId = context.deserialize(childJson, StructId.class); // recursion!
id.ChildId.ParentId = id;
}
return id;
}
}
I tested the code above with this JSON input example
{
"Name": "John",
"Type": "A",
"ChildId": {
"Name": "Jane",
"Type": "B",
"ChildId": {
"Name": "Joe",
"Type": "A"
}
}
}
by deserializing it with
StructId root = gson.fromJson(new FileReader("example.json"), StructId.class);,
then by serializing that with
System.out.println(gson.toJson(root));
and got the original JSON again.
Just to show one way to make serialization (so I do not handle de-serialization) with TypeAdapter and ExclusionStrategy. This might not be the most beautiful implementation but it is quite generic anyway.
This solution makes use of the fact that your struct is some kind of a bi-directional linked list and given any node in that list we just need to separate the serialization of parents and children so that those are serialized just in one direction to avoid circular references.
First we need configurable ExclusionStrategy like:
public class FieldExclusionStrategy implements ExclusionStrategy {
private final List<String> skipFields;
public FieldExclusionStrategy(String... fieldNames) {
skipFields = Arrays.asList(fieldNames);
}
#Override
public boolean shouldSkipField(FieldAttributes f) {
return skipFields.contains(f.getName());
}
#Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
}
Then the TypeAdapter would be like:
public class LinkedListAdapter extends TypeAdapter<StructId> {
private static final String PARENT_ID = "ParentId";
private static final String CHILD_ID = "ChildId";
private Gson gson;
#Override
public void write(JsonWriter out, StructId value) throws IOException {
// First serialize everything but StructIds
// You could also use type based exclusion strategy
// but for brevity I use just this one
gson = new GsonBuilder()
.addSerializationExclusionStrategy(
new FieldExclusionStrategy(CHILD_ID, PARENT_ID))
.create();
JsonObject structObject = gson.toJsonTree(value).getAsJsonObject();
JsonObject structParentObject;
JsonObject structChildObject;
// If exists go through the ParentId side in one direction.
if(null!=value.ParentId) {
gson = new GsonBuilder()
.addSerializationExclusionStrategy(new FieldExclusionStrategy(CHILD_ID))
.create();
structObject.add(PARENT_ID, gson.toJsonTree(value.ParentId));
if(null!=value.ParentId.ChildId) {
gson = new GsonBuilder()
.addSerializationExclusionStrategy(new FieldExclusionStrategy(PARENT_ID))
.create();
structParentObject = structObject.get(PARENT_ID).getAsJsonObject();
structParentObject.add(CHILD_ID, gson.toJsonTree(value.ParentId.ChildId).getAsJsonObject());
}
}
// And also if exists go through the ChildId side in one direction.
if(null!=value.ChildId) {
gson = new GsonBuilder()
.addSerializationExclusionStrategy(new FieldExclusionStrategy(PARENT_ID))
.create();
structObject.add(CHILD_ID, gson.toJsonTree(value.ChildId));
if(null!=value.ChildId.ParentId) {
gson = new GsonBuilder()
.addSerializationExclusionStrategy(new FieldExclusionStrategy(CHILD_ID))
.create();
structChildObject = structObject.get(CHILD_ID).getAsJsonObject();
structChildObject.add(PARENT_ID, gson.toJsonTree(value.ChildId.ParentId).getAsJsonObject());
}
}
// Finally write the combined result out. No need to initialize gson anymore
// since just writing JsonElement
gson.toJson(structObject, out);
}
#Override
public StructId read(JsonReader in) throws IOException {
return null;
}}
Testing it:
#Slf4j
public class TestIt extends BaseGsonTest {
#Test
public void test1() {
StructId grandParent = new StructId();
StructId parent = new StructId();
grandParent.ChildId = parent;
parent.ParentId = grandParent;
StructId child = new StructId();
parent.ChildId = child;
child.ParentId = parent;
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapter(StructId.class, new LinkedListAdapter())
.create();
log.info("\n{}", gson.toJson(parent));
}}
Would give you something like:
{
"Name": "name1237598030",
"Type": {
"name": "name688766789"
},
"ParentId": {
"Name": "name1169146729",
"Type": {
"name": "name2040352617"
}
},
"ChildId": {
"Name": "name302155142",
"Type": {
"name": "name24606376"
}
}
}
Names in my test material are just by default initialized with "name"+hashCode()
Sorry for misleading you guys, based on this post :
Is there a solution about Gson "circular reference"?
"there is no automated solution for circular references in Gson. The only JSON-producing library I know of that handles circular references automatically is XStream (with Jettison backend)."
But that is case you don't use Jackson! If you are using Jackson already for building your REST API controllers so why not to use it for making the serialization. No need for external compopnents like: Gson or XStream.
The solution with Jackson:
Serialization:
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
try {
jsonDesttinationIdString = ow.writeValueAsString(destinationId);
} catch (JsonProcessingException ex) {
throw new SpecificationException(ex.getMessage());
}
De-serialization:
ObjectMapper mapper = new ObjectMapper();
try {
destinationStructId = destinationId.isEmpty() ? null : mapper.readValue(URLDecoder.decode(destinationId, ENCODING), StructId.class);
} catch (IOException e) {
throw new SpecificationException(e.getMessage());
}
And most important, you must use the #JsonIdentityInfo annotation:
//#JsonIdentityInfo(
// generator = ObjectIdGenerators.PropertyGenerator.class,
// property = "Name")
#JsonIdentityInfo(
generator = ObjectIdGenerators.UUIDGenerator.class,
property = "id")
public class StructId implements Serializable {
private static final long serialVersionUID = 1L;
#JsonProperty("id") // I added this field to have a unique identfier
private UUID id = UUID.randomUUID();

Handle JSON which sends array of items but sometimes empty string in case of 0 elements

I have a JSON which sends array of element in normal cases but sends empty string "" tag without array [] brackets in case of 0 elements.
How to handle this with Gson? I want to ignore the error and not cause JSONParsingException.
eg.
"types": [
"Environment",
"Management",
"Computers"
],
sometimes it returns:
"types" : ""
Getting the following exception: Expected BEGIN ARRAY but was string
Since you don't have control over the input JSON string, you can test the content and decide what to do with it.
Here is an example of a working Java class:
import com.google.gson.Gson;
import java.util.ArrayList;
public class Test {
class Types {
Object types;
}
public void test(String input) {
Gson gson = new Gson();
Types types = gson.fromJson(input,Types.class);
if(types.types instanceof ArrayList) {
System.out.println("types is an ArrayList");
} else if (types.types instanceof String) {
System.out.println("types is an empty String");
}
}
public static void main(String[] args) {
String input = "{\"types\": [\n" +
" \"Environment\",\n" +
" \"Management\",\n" +
" \"Computers\"\n" +
" ]}";
String input2 = "{\"types\" : \"\"}";
Test testing = new Test();
testing.test(input2); //change input2 to input
}
}
If a bad JSON schema is not under your control, you can implement a specific type adapter that would try to determine whether the given JSON document is fine for you and, if possible, make some transformations. I would recomment to use #JsonAdapter in order to specify improperly designed types (at least I hope the entire API is not improperly designed).
For example,
final class Wrapper {
#JsonAdapter(LenientListTypeAdapterFactory.class)
final List<String> types = null;
}
where LenientListTypeAdapterFactory can be implemented as follows:
final class LenientListTypeAdapterFactory
implements TypeAdapterFactory {
// Gson can instantiate it itself, let it just do it
private LenientListTypeAdapterFactory() {
}
#Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> typeToken) {
// Obtaining the original list type adapter
#SuppressWarnings("unchecked")
final TypeAdapter<List<?>> realListTypeAdapter = (TypeAdapter<List<?>>) gson.getAdapter(typeToken);
// And wrap it up in the lenient JSON type adapter
#SuppressWarnings("unchecked")
final TypeAdapter<T> castTypeAdapter = (TypeAdapter<T>) new LenientListTypeAdapter(realListTypeAdapter);
return castTypeAdapter;
}
private static final class LenientListTypeAdapter
extends TypeAdapter<List<?>> {
private final TypeAdapter<List<?>> realListTypeAdapter;
private LenientListTypeAdapter(final TypeAdapter<List<?>> realListTypeAdapter) {
this.realListTypeAdapter = realListTypeAdapter;
}
#Override
public void write(final JsonWriter out, final List<?> value)
throws IOException {
realListTypeAdapter.write(out, value);
}
#Override
public List<?> read(final JsonReader in)
throws IOException {
// Check the next (effectively current) JSON token
switch ( in.peek() ) {
// If it's either `[...` or `null` -- we're supposing it's a "normal" list
case BEGIN_ARRAY:
case NULL:
return realListTypeAdapter.read(in);
// Is it a string?
case STRING:
// Skip the value entirely
in.skipValue();
// And return a new array list.
// Note that you might return emptyList() but Gson uses mutable lists so we do either
return new ArrayList<>();
// Not anything known else?
case END_ARRAY:
case BEGIN_OBJECT:
case END_OBJECT:
case NAME:
case NUMBER:
case BOOLEAN:
case END_DOCUMENT:
// Something definitely unexpected
throw new MalformedJsonException("Cannot parse " + in);
default:
// This would never happen unless Gson adds a new type token
throw new AssertionError();
}
}
}
}
Here is it how it can be tested:
for ( final String name : ImmutableList.of("3-elements.json", "0-elements.json") ) {
try ( final Reader reader = getPackageResourceReader(Q43562427.class, name) ) {
final Wrapper wrapper = gson.fromJson(reader, Wrapper.class);
System.out.println(wrapper.types);
}
}
Output:
[Environment, Management, Computers]
[]
If the entire API uses "" for empty arrays, then you can drop the #JsonAdapter annotation and register the LenientListTypeAdapterFactory via GsonBuilder, but add the following lines to the create method in order not to break other type adapters:
if ( !List.class.isAssignableFrom(typeToken.getRawType()) ) {
// This tells Gson to try to pick up the next best-match type adapter
return null;
}
...
There are a lot of weirdly designed JSON response choices, but this one hits the top #1 issue where nulls or empties are represented with "". Good luck!
Thanks for all your answers.
The recommed way as mentioned in above answers would be to use TypeAdapters and ExclusionStrategy for GSON.
Here is a good example Custom GSON desrialization

How to use parsed String from JSON [duplicate]

I have the following JSON text. How can I parse it to get the values of pageName, pagePic, post_id, etc.?
{
"pageInfo": {
"pageName": "abc",
"pagePic": "http://example.com/content.jpg"
},
"posts": [
{
"post_id": "123456789012_123456789012",
"actor_id": "1234567890",
"picOfPersonWhoPosted": "http://example.com/photo.jpg",
"nameOfPersonWhoPosted": "Jane Doe",
"message": "Sounds cool. Can't wait to see it!",
"likesCount": "2",
"comments": [],
"timeOfPost": "1234567890"
}
]
}
The org.json library is easy to use.
Just remember (while casting or using methods like getJSONObject and getJSONArray) that in JSON notation
[ … ] represents an array, so library will parse it to JSONArray
{ … } represents an object, so library will parse it to JSONObject
Example code below:
import org.json.*;
String jsonString = ... ; //assign your JSON String here
JSONObject obj = new JSONObject(jsonString);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");
JSONArray arr = obj.getJSONArray("posts"); // notice that `"posts": [...]`
for (int i = 0; i < arr.length(); i++)
{
String post_id = arr.getJSONObject(i).getString("post_id");
......
}
You may find more examples from: Parse JSON in Java
Downloadable jar: http://mvnrepository.com/artifact/org.json/json
For the sake of the example lets assume you have a class Person with just a name.
private class Person {
public String name;
public Person(String name) {
this.name = name;
}
}
Google GSON (Maven)
My personal favourite as to the great JSON serialisation / de-serialisation of objects.
Gson g = new Gson();
Person person = g.fromJson("{\"name\": \"John\"}", Person.class);
System.out.println(person.name); //John
System.out.println(g.toJson(person)); // {"name":"John"}
Update
If you want to get a single attribute out you can do it easily with the Google library as well:
JsonObject jsonObject = new JsonParser().parse("{\"name\": \"John\"}").getAsJsonObject();
System.out.println(jsonObject.get("name").getAsString()); //John
Org.JSON (Maven)
If you don't need object de-serialisation but to simply get an attribute, you can try org.json (or look GSON example above!)
JSONObject obj = new JSONObject("{\"name\": \"John\"}");
System.out.println(obj.getString("name")); //John
Jackson (Maven)
ObjectMapper mapper = new ObjectMapper();
Person user = mapper.readValue("{\"name\": \"John\"}", Person.class);
System.out.println(user.name); //John
If one wants to create Java object from JSON and vice versa, use GSON or JACKSON third party jars etc.
//from object to JSON
Gson gson = new Gson();
gson.toJson(yourObject);
// from JSON to object
yourObject o = gson.fromJson(JSONString,yourObject.class);
But if one just want to parse a JSON string and get some values, (OR create a JSON string from scratch to send over wire) just use JaveEE jar which contains JsonReader, JsonArray, JsonObject etc. You may want to download the implementation of that spec like javax.json. With these two jars I am able to parse the json and use the values.
These APIs actually follow the DOM/SAX parsing model of XML.
Response response = request.get(); // REST call
JsonReader jsonReader = Json.createReader(new StringReader(response.readEntity(String.class)));
JsonArray jsonArray = jsonReader.readArray();
ListIterator l = jsonArray.listIterator();
while ( l.hasNext() ) {
JsonObject j = (JsonObject)l.next();
JsonObject ciAttr = j.getJsonObject("ciAttributes");
quick-json parser is very straightforward, flexible, very fast and customizable. Try it
Features:
Compliant with JSON specification (RFC4627)
High-Performance JSON parser
Supports Flexible/Configurable parsing approach
Configurable validation of key/value pairs of any JSON Hierarchy
Easy to use # Very small footprint
Raises developer friendly and easy to trace exceptions
Pluggable Custom Validation support - Keys/Values can be validated by configuring custom validators as and when encountered
Validating and Non-Validating parser support
Support for two types of configuration (JSON/XML) for using quick-JSON validating parser
Requires JDK 1.5
No dependency on external libraries
Support for JSON Generation through object serialisation
Support for collection type selection during parsing process
It can be used like this:
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);
You could use Google Gson.
Using this library you only need to create a model with the same JSON structure. Then the model is automatically filled in. You have to call your variables as your JSON keys, or use #SerializedName if you want to use different names.
JSON
From your example:
{
"pageInfo": {
"pageName": "abc",
"pagePic": "http://example.com/content.jpg"
}
"posts": [
{
"post_id": "123456789012_123456789012",
"actor_id": "1234567890",
"picOfPersonWhoPosted": "http://example.com/photo.jpg",
"nameOfPersonWhoPosted": "Jane Doe",
"message": "Sounds cool. Can't wait to see it!",
"likesCount": "2",
"comments": [],
"timeOfPost": "1234567890"
}
]
}
Model
class MyModel {
private PageInfo pageInfo;
private ArrayList<Post> posts = new ArrayList<>();
}
class PageInfo {
private String pageName;
private String pagePic;
}
class Post {
private String post_id;
#SerializedName("actor_id") // <- example SerializedName
private String actorId;
private String picOfPersonWhoPosted;
private String nameOfPersonWhoPosted;
private String message;
private String likesCount;
private ArrayList<String> comments;
private String timeOfPost;
}
Parsing
Now you can parse using Gson library:
MyModel model = gson.fromJson(jsonString, MyModel.class);
Gradle import
Remember to import the library in the app Gradle file
implementation 'com.google.code.gson:gson:2.8.6' // or earlier versions
Automatic model generation
You can generate model from JSON automatically using online tools like this.
A - Explanation
You can use Jackson libraries, for binding JSON String into POJO (Plain Old Java Object) instances. POJO is simply a class with only private fields and public getter/setter methods. Jackson is going to traverse the methods (using reflection), and maps the JSON object into the POJO instance as the field names of the class fits to the field names of the JSON object.
In your JSON object, which is actually a composite object, the main object consists o two sub-objects. So, our POJO classes should have the same hierarchy. I'll call the whole JSON Object as Page object. Page object consist of a PageInfo object, and a Post object array.
So we have to create three different POJO classes;
Page Class, a composite of PageInfo Class and array of Post Instances
PageInfo Class
Posts Class
The only package I've used is Jackson ObjectMapper, what we do is binding data;
com.fasterxml.jackson.databind.ObjectMapper
The required dependencies, the jar files is listed below;
jackson-core-2.5.1.jar
jackson-databind-2.5.1.jar
jackson-annotations-2.5.0.jar
Here is the required code;
B - Main POJO Class : Page
package com.levo.jsonex.model;
public class Page {
private PageInfo pageInfo;
private Post[] posts;
public PageInfo getPageInfo() {
return pageInfo;
}
public void setPageInfo(PageInfo pageInfo) {
this.pageInfo = pageInfo;
}
public Post[] getPosts() {
return posts;
}
public void setPosts(Post[] posts) {
this.posts = posts;
}
}
C - Child POJO Class : PageInfo
package com.levo.jsonex.model;
public class PageInfo {
private String pageName;
private String pagePic;
public String getPageName() {
return pageName;
}
public void setPageName(String pageName) {
this.pageName = pageName;
}
public String getPagePic() {
return pagePic;
}
public void setPagePic(String pagePic) {
this.pagePic = pagePic;
}
}
D - Child POJO Class : Post
package com.levo.jsonex.model;
public class Post {
private String post_id;
private String actor_id;
private String picOfPersonWhoPosted;
private String nameOfPersonWhoPosted;
private String message;
private int likesCount;
private String[] comments;
private int timeOfPost;
public String getPost_id() {
return post_id;
}
public void setPost_id(String post_id) {
this.post_id = post_id;
}
public String getActor_id() {
return actor_id;
}
public void setActor_id(String actor_id) {
this.actor_id = actor_id;
}
public String getPicOfPersonWhoPosted() {
return picOfPersonWhoPosted;
}
public void setPicOfPersonWhoPosted(String picOfPersonWhoPosted) {
this.picOfPersonWhoPosted = picOfPersonWhoPosted;
}
public String getNameOfPersonWhoPosted() {
return nameOfPersonWhoPosted;
}
public void setNameOfPersonWhoPosted(String nameOfPersonWhoPosted) {
this.nameOfPersonWhoPosted = nameOfPersonWhoPosted;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getLikesCount() {
return likesCount;
}
public void setLikesCount(int likesCount) {
this.likesCount = likesCount;
}
public String[] getComments() {
return comments;
}
public void setComments(String[] comments) {
this.comments = comments;
}
public int getTimeOfPost() {
return timeOfPost;
}
public void setTimeOfPost(int timeOfPost) {
this.timeOfPost = timeOfPost;
}
}
E - Sample JSON File : sampleJSONFile.json
I've just copied your JSON sample into this file and put it under the project folder.
{
"pageInfo": {
"pageName": "abc",
"pagePic": "http://example.com/content.jpg"
},
"posts": [
{
"post_id": "123456789012_123456789012",
"actor_id": "1234567890",
"picOfPersonWhoPosted": "http://example.com/photo.jpg",
"nameOfPersonWhoPosted": "Jane Doe",
"message": "Sounds cool. Can't wait to see it!",
"likesCount": "2",
"comments": [],
"timeOfPost": "1234567890"
}
]
}
F - Demo Code
package com.levo.jsonex;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.levo.jsonex.model.Page;
import com.levo.jsonex.model.PageInfo;
import com.levo.jsonex.model.Post;
public class JSONDemo {
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
try {
Page page = objectMapper.readValue(new File("sampleJSONFile.json"), Page.class);
printParsedObject(page);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void printParsedObject(Page page) {
printPageInfo(page.getPageInfo());
System.out.println();
printPosts(page.getPosts());
}
private static void printPageInfo(PageInfo pageInfo) {
System.out.println("Page Info;");
System.out.println("**********");
System.out.println("\tPage Name : " + pageInfo.getPageName());
System.out.println("\tPage Pic : " + pageInfo.getPagePic());
}
private static void printPosts(Post[] posts) {
System.out.println("Page Posts;");
System.out.println("**********");
for(Post post : posts) {
printPost(post);
}
}
private static void printPost(Post post) {
System.out.println("\tPost Id : " + post.getPost_id());
System.out.println("\tActor Id : " + post.getActor_id());
System.out.println("\tPic Of Person Who Posted : " + post.getPicOfPersonWhoPosted());
System.out.println("\tName Of Person Who Posted : " + post.getNameOfPersonWhoPosted());
System.out.println("\tMessage : " + post.getMessage());
System.out.println("\tLikes Count : " + post.getLikesCount());
System.out.println("\tComments : " + Arrays.toString(post.getComments()));
System.out.println("\tTime Of Post : " + post.getTimeOfPost());
}
}
G - Demo Output
Page Info;
****(*****
Page Name : abc
Page Pic : http://example.com/content.jpg
Page Posts;
**********
Post Id : 123456789012_123456789012
Actor Id : 1234567890
Pic Of Person Who Posted : http://example.com/photo.jpg
Name Of Person Who Posted : Jane Doe
Message : Sounds cool. Can't wait to see it!
Likes Count : 2
Comments : []
Time Of Post : 1234567890
Almost all the answers given requires a full deserialization of the JSON into a Java object before accessing the value in the property of interest. Another alternative, which does not go this route is to use JsonPATH which is like XPath for JSON and allows traversing of JSON objects.
It is a specification and the good folks at JayWay have created a Java implementation for the specification which you can find here: https://github.com/jayway/JsonPath
So basically to use it, add it to your project, eg:
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>${version}</version>
</dependency>
and to use:
String pageName = JsonPath.read(yourJsonString, "$.pageInfo.pageName");
String pagePic = JsonPath.read(yourJsonString, "$.pageInfo.pagePic");
String post_id = JsonPath.read(yourJsonString, "$.pagePosts[0].post_id");
etc...
Check the JsonPath specification page for more information on the other ways to transverse JSON.
Use minimal-json which is very fast and easy to use.
You can parse from String obj and Stream.
Sample data:
{
"order": 4711,
"items": [
{
"name": "NE555 Timer IC",
"cat-id": "645723",
"quantity": 10,
},
{
"name": "LM358N OpAmp IC",
"cat-id": "764525",
"quantity": 2
}
]
}
Parsing:
JsonObject object = Json.parse(input).asObject();
int orders = object.get("order").asInt();
JsonArray items = object.get("items").asArray();
Creating JSON:
JsonObject user = Json.object().add("name", "Sakib").add("age", 23);
Maven:
<dependency>
<groupId>com.eclipsesource.minimal-json</groupId>
<artifactId>minimal-json</artifactId>
<version>0.9.4</version>
</dependency>
The below example shows how to read the text in the question, represented as the "jsonText" variable. This solution uses the Java EE7 javax.json API (which is mentioned in some of the other answers). The reason I've added it as a separate answer is that the following code shows how to actually access some of the values shown in the question. An implementation of the javax.json API would be required to make this code run. The full package for each of the classes required was included as I didn't want to declare "import" statements.
javax.json.JsonReader jr =
javax.json.Json.createReader(new StringReader(jsonText));
javax.json.JsonObject jo = jr.readObject();
//Read the page info.
javax.json.JsonObject pageInfo = jo.getJsonObject("pageInfo");
System.out.println(pageInfo.getString("pageName"));
//Read the posts.
javax.json.JsonArray posts = jo.getJsonArray("posts");
//Read the first post.
javax.json.JsonObject post = posts.getJsonObject(0);
//Read the post_id field.
String postId = post.getString("post_id");
Now, before anyone goes and downvotes this answer because it doesn't use GSON, org.json, Jackson, or any of the other 3rd party frameworks available, it's an example of "required code" per the question to parse the provided text. I am well aware that adherence to the current standard JSR 353 was not being considered for JDK 9 and as such the JSR 353 spec should be treated the same as any other 3rd party JSON handling implementation.
Since nobody mentioned it yet, here is a beginning of a solution using Nashorn (JavaScript runtime part of Java 8, but deprecated in Java 11).
Solution
private static final String EXTRACTOR_SCRIPT =
"var fun = function(raw) { " +
"var json = JSON.parse(raw); " +
"return [json.pageInfo.pageName, json.pageInfo.pagePic, json.posts[0].post_id];};";
public void run() throws ScriptException, NoSuchMethodException {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval(EXTRACTOR_SCRIPT);
Invocable invocable = (Invocable) engine;
JSObject result = (JSObject) invocable.invokeFunction("fun", JSON);
result.values().forEach(e -> System.out.println(e));
}
Performance comparison
I wrote JSON content containing three arrays of respectively 20, 20 and 100 elements. I only want to get the 100 elements from the third array. I use the following JavaScript function to parse and get my entries.
var fun = function(raw) {JSON.parse(raw).entries};
Running the call a million times using Nashorn takes 7.5~7.8 seconds
(JSObject) invocable.invokeFunction("fun", json);
org.json takes 20~21 seconds
new JSONObject(JSON).getJSONArray("entries");
Jackson takes 6.5~7 seconds
mapper.readValue(JSON, Entries.class).getEntries();
In this case Jackson performs better than Nashorn, which performs much better than org.json.
Nashorn API is harder to use than org.json's or Jackson's. Depending on your requirements Jackson and Nashorn both can be viable solutions.
I believe the best practice should be to go through the official Java JSON API which are still work in progress.
There are many JSON libraries available in Java.
The most notorious ones are: Jackson, GSON, Genson, FastJson and org.json.
There are typically three things one should look at for choosing any library:
Performance
Ease of use (code is simple to write and legible) - that goes with features.
For mobile apps: dependency/jar size
Specifically for JSON libraries (and any serialization/deserialization libs), databinding is also usually of interest as it removes the need of writing boiler-plate code to pack/unpack the data.
For 1, see this benchmark: https://github.com/fabienrenaud/java-json-benchmark I did using JMH which compares (jackson, gson, genson, fastjson, org.json, jsonp) performance of serializers and deserializers using stream and databind APIs.
For 2, you can find numerous examples on the Internet. The benchmark above can also be used as a source of examples...
Quick takeaway of the benchmark: Jackson performs 5 to 6 times better than org.json and more than twice better than GSON.
For your particular example, the following code decodes your json with jackson:
public class MyObj {
private PageInfo pageInfo;
private List<Post> posts;
static final class PageInfo {
private String pageName;
private String pagePic;
}
static final class Post {
private String post_id;
#JsonProperty("actor_id");
private String actorId;
#JsonProperty("picOfPersonWhoPosted")
private String pictureOfPoster;
#JsonProperty("nameOfPersonWhoPosted")
private String nameOfPoster;
private String likesCount;
private List<String> comments;
private String timeOfPost;
}
private static final ObjectMapper JACKSON = new ObjectMapper();
public static void main(String[] args) throws IOException {
MyObj o = JACKSON.readValue(args[0], MyObj.class); // assumes args[0] contains your json payload provided in your question.
}
}
Let me know if you have any questions.
This blew my mind with how easy it was. You can just pass a String holding your JSON to the constructor of a JSONObject in the default org.json package.
JSONArray rootOfPage = new JSONArray(JSONString);
Done. Drops microphone.
This works with JSONObjects as well. After that, you can just look through your hierarchy of Objects using the get() methods on your objects.
In addition to other answers, I recomend this online opensource service jsonschema2pojo.org for quick generating Java classes from json or json schema for GSON, Jackson 1.x or Jackson 2.x. For example, if you have:
{
"pageInfo": {
"pageName": "abc",
"pagePic": "http://example.com/content.jpg"
}
"posts": [
{
"post_id": "123456789012_123456789012",
"actor_id": 1234567890,
"picOfPersonWhoPosted": "http://example.com/photo.jpg",
"nameOfPersonWhoPosted": "Jane Doe",
"message": "Sounds cool. Can't wait to see it!",
"likesCount": 2,
"comments": [],
"timeOfPost": 1234567890
}
]
}
The jsonschema2pojo.org for GSON generated:
#Generated("org.jsonschema2pojo")
public class Container {
#SerializedName("pageInfo")
#Expose
public PageInfo pageInfo;
#SerializedName("posts")
#Expose
public List<Post> posts = new ArrayList<Post>();
}
#Generated("org.jsonschema2pojo")
public class PageInfo {
#SerializedName("pageName")
#Expose
public String pageName;
#SerializedName("pagePic")
#Expose
public String pagePic;
}
#Generated("org.jsonschema2pojo")
public class Post {
#SerializedName("post_id")
#Expose
public String postId;
#SerializedName("actor_id")
#Expose
public long actorId;
#SerializedName("picOfPersonWhoPosted")
#Expose
public String picOfPersonWhoPosted;
#SerializedName("nameOfPersonWhoPosted")
#Expose
public String nameOfPersonWhoPosted;
#SerializedName("message")
#Expose
public String message;
#SerializedName("likesCount")
#Expose
public long likesCount;
#SerializedName("comments")
#Expose
public List<Object> comments = new ArrayList<Object>();
#SerializedName("timeOfPost")
#Expose
public long timeOfPost;
}
If you have some Java class(say Message) representing the JSON string(jsonString), you can use Jackson JSON library with:
Message message= new ObjectMapper().readValue(jsonString, Message.class);
and from message object you can fetch any of its attribute.
Gson is easy to learn and implement, what we need to know are following two methods
toJson() – Convert Java object to JSON format
fromJson() – Convert JSON into Java object
`
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;
public class GsonExample {
public static void main(String[] args) {
Gson gson = new Gson();
try {
BufferedReader br = new BufferedReader(
new FileReader("c:\\file.json"));
//convert the json string back to object
DataObject obj = gson.fromJson(br, DataObject.class);
System.out.println(obj);
} catch (IOException e) {
e.printStackTrace();
}
}
}
`
There are many open source libraries present to parse JSON content to an object or just to read JSON values. Your requirement is just to read values and parsing it to custom object. So org.json library is enough in your case.
Use org.json library to parse it and create JsonObject:
JSONObject jsonObj = new JSONObject(<jsonStr>);
Now, use this object to get your values:
String id = jsonObj.getString("pageInfo");
You can see a complete example here:
How to parse JSON in Java
You can use the Gson Library to parse the JSON string.
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonAsString, JsonObject.class);
String pageName = jsonObject.getAsJsonObject("pageInfo").get("pageName").getAsString();
String pagePic = jsonObject.getAsJsonObject("pageInfo").get("pagePic").getAsString();
String postId = jsonObject.getAsJsonArray("posts").get(0).getAsJsonObject().get("post_id").getAsString();
You can also loop through the "posts" array as so:
JsonArray posts = jsonObject.getAsJsonArray("posts");
for (JsonElement post : posts) {
String postId = post.getAsJsonObject().get("post_id").getAsString();
//do something
}
Read the following blog post, JSON in Java.
This post is a little bit old, but still I want to answer you question.
Step 1: Create a POJO class of your data.
Step 2: Now create a object using JSON.
Employee employee = null;
ObjectMapper mapper = new ObjectMapper();
try {
employee = mapper.readValue(newFile("/home/sumit/employee.json"), Employee.class);
}
catch(JsonGenerationException e) {
e.printStackTrace();
}
For further reference you can refer to the following link.
You can use Jayway JsonPath. Below is a GitHub link with source code, pom details and good documentation.
https://github.com/jayway/JsonPath
Please follow the below steps.
Step 1: Add the jayway JSON path dependency in your class path using Maven or download the JAR file and manually add it.
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
</dependency>
Step 2: Please save your input JSON as a file for this example. In my case I saved your JSON as sampleJson.txt. Note you missed a comma between pageInfo and posts.
Step 3: Read the JSON contents from the above file using bufferedReader and save it as String.
BufferedReader br = new BufferedReader(new FileReader("D:\\sampleJson.txt"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
br.close();
String jsonInput = sb.toString();
Step 4: Parse your JSON string using jayway JSON parser.
Object document = Configuration.defaultConfiguration().jsonProvider().parse(jsonInput);
Step 5: Read the details like below.
String pageName = JsonPath.read(document, "$.pageInfo.pageName");
String pagePic = JsonPath.read(document, "$.pageInfo.pagePic");
String post_id = JsonPath.read(document, "$.posts[0].post_id");
System.out.println("$.pageInfo.pageName " + pageName);
System.out.println("$.pageInfo.pagePic " + pagePic);
System.out.println("$.posts[0].post_id " + post_id);
The output will be:
$.pageInfo.pageName = abc
$.pageInfo.pagePic = http://example.com/content.jpg
$.posts[0].post_id = 123456789012_123456789012
I have JSON like this:
{
"pageInfo": {
"pageName": "abc",
"pagePic": "http://example.com/content.jpg"
}
}
Java class
class PageInfo {
private String pageName;
private String pagePic;
// Getters and setters
}
Code for converting this JSON to a Java class.
PageInfo pageInfo = JsonPath.parse(jsonString).read("$.pageInfo", PageInfo.class);
Maven
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
</dependency>
Please do something like this:
JSONParser jsonParser = new JSONParser();
JSONObject obj = (JSONObject) jsonParser.parse(contentString);
String product = (String) jsonObject.get("productId");
{
"pageInfo": {
"pageName": "abc",
"pagePic": "http://example.com/content.jpg"
},
"posts": [
{
"post_id": "123456789012_123456789012",
"actor_id": "1234567890",
"picOfPersonWhoPosted": "http://example.com/photo.jpg",
"nameOfPersonWhoPosted": "Jane Doe",
"message": "Sounds cool. Can't wait to see it!",
"likesCount": "2",
"comments": [],
"timeOfPost": "1234567890"
}
]
}
Java code :
JSONObject obj = new JSONObject(responsejsonobj);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");
JSONArray arr = obj.getJSONArray("posts");
for (int i = 0; i < arr.length(); i++)
{
String post_id = arr.getJSONObject(i).getString("post_id");
......etc
}
First you need to select an implementation library to do that.
The Java API for JSON Processing (JSR 353) provides portable APIs to parse, generate, transform, and query JSON using object model and streaming APIs.
The reference implementation is here: https://jsonp.java.net/
Here you can find a list of implementations of JSR 353:
What are the API that does implement JSR-353 (JSON)
And to help you decide... I found this article as well:
http://blog.takipi.com/the-ultimate-json-library-json-simple-vs-gson-vs-jackson-vs-json/
If you go for Jackson, here is a good article about conversion between JSON to/from Java using Jackson: https://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
Hope it helps!
Top answers on this page use too simple examples like object with one property (e.g. {name: value}). I think that still simple but real life example can help someone.
So this is the JSON returned by Google Translate API:
{
"data":
{
"translations":
[
{
"translatedText": "Arbeit"
}
]
}
}
I want to retrieve the value of "translatedText" attribute e.g. "Arbeit" using Google's Gson.
Two possible approaches:
Retrieve just one needed attribute
String json = callToTranslateApi("work", "de");
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
return jsonObject.get("data").getAsJsonObject()
.get("translations").getAsJsonArray()
.get(0).getAsJsonObject()
.get("translatedText").getAsString();
Create Java object from JSON
class ApiResponse {
Data data;
class Data {
Translation[] translations;
class Translation {
String translatedText;
}
}
}
...
Gson g = new Gson();
String json =callToTranslateApi("work", "de");
ApiResponse response = g.fromJson(json, ApiResponse.class);
return response.data.translations[0].translatedText;
If you have maven project then add below dependency or normal project add json-simple jar.
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
Write below java code for convert JSON string to JSON array.
JSONArray ja = new JSONArray(String jsonString);
Any kind of json array
steps to solve the issue.
Convert your JSON object to a java object.
You can use this link or any online tool.
Save out as a java class like Myclass.java.
Myclass obj = new Gson().fromJson(JsonStr, Myclass.class);
Using obj, you can get your values.
One can use Apache #Model annotation to create Java model classes representing structure of JSON files and use them to access various elements in the JSON tree. Unlike other solutions this one works completely without reflection and is thus suitable for environments where reflection is impossible or comes with significant overhead.
There is a sample Maven project showing the usage. First of all it defines the structure:
#Model(className="RepositoryInfo", properties = {
#Property(name = "id", type = int.class),
#Property(name = "name", type = String.class),
#Property(name = "owner", type = Owner.class),
#Property(name = "private", type = boolean.class),
})
final class RepositoryCntrl {
#Model(className = "Owner", properties = {
#Property(name = "login", type = String.class)
})
static final class OwnerCntrl {
}
}
and then it uses the generated RepositoryInfo and Owner classes to parse the provided input stream and pick certain information up while doing that:
List<RepositoryInfo> repositories = new ArrayList<>();
try (InputStream is = initializeStream(args)) {
Models.parse(CONTEXT, RepositoryInfo.class, is, repositories);
}
System.err.println("there is " + repositories.size() + " repositories");
repositories.stream().filter((repo) -> repo != null).forEach((repo) -> {
System.err.println("repository " + repo.getName() +
" is owned by " + repo.getOwner().getLogin()
);
})
That is it! In addition to that here is a live gist showing similar example together with asynchronous network communication.
jsoniter (jsoniterator) is a relatively new and simple json library, designed to be simple and fast. All you need to do to deserialize json data is
JsonIterator.deserialize(jsonData, int[].class);
where jsonData is a string of json data.
Check out the official website
for more information.
You can use JsonNode for a structured tree representation of your JSON string. It's part of the rock solid jackson library which is omnipresent.
ObjectMapper mapper = new ObjectMapper();
JsonNode yourObj = mapper.readTree("{\"k\":\"v\"}");

FlexJson deserialize object reference

I'm using Spring Roo which generated set of hibernate and FlexJSON classes.
I have entity called Location and entity called Comment.
Location has many comments (1:M).
I'm trying to generate JSON object, which will, when deserialized and inserted reference existing Location object.
When I omit location field, everything is working fine, for example:
{
"date": 1315918228639,
"comment": "Bosnia is very nice country"
}
I don't know how to reference location field.
I've tried following, but with little success:
{
"location": 10,
"date": 1315918228639,
"comment": "Bosnia is very nice country"
}
where location id is 10.
How can I reference location field in the JSON?
Edit: Added Comment entity:
#RooJavaBean
#RooToString
#RooJson
#RooEntity
public class Komentar {
private String comment;
#ManyToOne
private Location location;
#Temporal(TemporalType.TIMESTAMP)
#DateTimeFormat(style = "M-")
private Date date;
}
I've solved issue by adding transient property.
#Transient
public long getLocationId(){
if(location!=null)
return location.getId();
else
return -1;
}
#Transient
public void setLocationId(long id){
location = Location.findLocation(id);
}
Got similar problem, but i can't change incoming json message, so i've changed generated aspect file:
#RequestMapping(value = "/jsonArray", method = RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity<String> Komentar.createFromJsonArray(#RequestBody String json) {
for (Komentar komentar: Komentar.fromJsonArrayToProducts(json)) {
komentar.setLocation(Location.findLocation(komentar.getLocation().getId()));
komentar.persist();
}
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
return new ResponseEntity<String>(headers, HttpStatus.CREATED);
}
komentar.setLocation(Location.findLocation(komentar.getLocation().getId())); was added by me.
I got same problem and solved it by introducing a custom object factory.
Since JSONDeserializer expect a json object for location attribute (ex:"Location":{"id":10,..}), supplying location id as a String/Integer (ex:"Location":"10") will give you an exception.
Therefore I have written LocationObjectFactory class and telling flexjson how to deserialize a Location class object in the way I want.
public class LocationObjectFactory implements ObjectFactory {
#Override
public Object instantiate(ObjectBinder context, Object value,
Type targetType, Class targetClass) {
if(value instanceof String){
return Location.findProblem(Long.parseLong((String)value));
}
if(value instanceof Integer){
return Location.findProblem(((Integer)value).longValue());
}
else {
throw context.cannotConvertValueToTargetType(value,targetClass);
}
}
}
and deserialize the json string like this
new JSONDeserializer<Komentar>().use(null, Komentar.class).use(Location.class, new LocationObjectFactory()).deserialize(json);