Adding nested values using JsonPath in Java - java

I'm using JsonPath in Java, and I'd like to know if there's a way to use the path specifications to add nested values. The following example will clarify.
I have this json
{"attr1":"value1"}
Since I need to work on the json a lot, and I do not want to parse it every time (according to the documentation), I load the json in the following way
String sJson = "{\"attr1\":\"value1\"}"
Object json = Configuration.defaultConfiguration().jsonProvider().parse(sJson);
and I'd like to add a value so that the final json is
{"attr1":"value1","attr2":{"nested_attr1":"nested_value1"}}
What's the best way to add attr2 to obtain that result? Is there a way in which I can use the JsonPath syntax (attr2.nested_value1)?
If I use
Configuration.defaultConfiguration().jsonProvider().setProperty(json, "attr2.nested_attr1", "nested_value1");
what I obtain is an updated json like
{"attr1":"value1","attr2.nested_attr1":"nested_value1"}
and this because setProperty do not work with paths. I tried using
JsonPath.parse(json).put("$", "attr2.nested_attr1", "nested_value1"").jsonString();
but yet I have to parse the json every time back and forth, and second I obtain the same result as before. Is there a way to handle this problem, or do I have to implement the nested add by myself?

Related

How to convert JsonForm to Json?

I would like to extract only the data present in a Json to JsonForm using Java.
Which framework can I use to this operation?
I've found the answer. Don't let the ugly aspect of JsonForm deceive you. I don't know if this apply for all cases, but I just had to extract the Json object that contains only the data. This can be done using any common Json parser, as like as Gson.

How to extract nested JSON Elements in Liferay

I'm using Liferay 6.2 and have a JSONObject containing the following:
{
"foo":{
"bar":{
"baz":["42","23"]
}
}
}
I have a String containing a path/selector/whatsitcalled pointing somewhere in that JSONObject: foo.bar.baz[0]
How would I go about getting the corresponding value from the JSONObject, i.e. "42"?
All methods I could find only deal with the next level down, nothing seems to cover nesting. I could parse the path manually, but isn't there an easier way?
Use this java library to perform xpath similar query for json.
I've used it with success in Liferay.
https://github.com/jayway/JsonPath
There are many ways to retrive data programatically from JSON object.
You can use the own Liferay support JSON library, GSON or Jackson libraries ( I recommend you the last one, it is really powerful).

Gson: fields that sometimes are strings and others arrays

I'm parsing json with Gson but I'm struggling with the data I'm getting. This is part of an API out of my control (openFDA) so changing that might not be an option.
Here's the json I'm strugling with: https://api.fda.gov/device/event.json?search=device.generic_name:generator&limit=10
There are some fields that are not consistent, for example remedial_action. Sometimes it comes out like this:
"remedial_action": [
"Recall"
]
and in other results like this:
"remedial_action": ""
So it's either an array or a plain string. Is there a way to handle this? If not possible in Gson, any other json parsing library that can help?
I created my pojos here in case someone needs the code. There are a few files created from that and didn't want to spam them here. I can add them if needed.
Update: The bug has been confirmed and it's scheduled for a fix.
It is possible through GSON, by using a TypeAdapter.
Here are the initial steps I would use to do that:
Create a POJO that contains the array and the String. Let's call it RemedialAction.
In your original POJO, create an attribute of the new class.
Create a class that extends TypeAdapter<RemedialAction>.
Override the read() and write() methods and create the logic in them.
That should be a little hard to parse, though. Read this tutorial for more information.
Note: you can customize getRemedialAction() to give you only the valid return -- array or String.

Parsing a cypher query result (JSON) to a Java object

I use the jersey/jackson stack to address a neo4j database via the REST api, but I have some issues how to interpret the result.
If I read the node by its ID (/db/data/node/xxx) the result can be mapped to my DTO very easy by calling readEntity(MyDto.class) on the response. However, usage of internal IDs is not recommended and various use cases require to query by custom properties. Here cypher comes into play (/db/data/cypher).
Assuming a node exists with a property "myid" and a value of "1234", I can fetch it with the cypher query "MATCH (n {myid: 1234}) RETURN n". The result is a JSON string with a bunch of resources and eventually the "data" I want do unmarshall to a java object. Unmarshalling it directly fails with a ProcessingException (error reading entity from input stream). I see no API allowing to iterate the result's data.
My idea is to define some kind of generic wrapper class with an attribute "data", giving this one to the unmarshaller, and unwrapping my DTO afterwards. I wonder if there is a more elegant way to do this, like using "RETURN n.data" (which does not work) or something like this. Is it?
You should look into neo4j 2.0 where return n just returns the property map.
I usually tend to deserialize the result as a nested list/map (i.e. have ObjectMapper read to Object.class or Map.class) structure and grab the data map directly out of that.
There's probably a way to tell jackson to ignore all the information around that data field
If you want to have a nicer presentation you can also check out my cypher-rs project which returns only the data in question, nothing more.

How to pass an array of objects from javascript to Java

Hello Im trying to pass an array of objects from javascript to java , but how can this be done..??
I've found in some posts that they do this using a hidden input. Is this the only way?
I'm a bit confused. Please tell me what do I need to do to pass my array to the server? and which javascript files and jars do I need to add?
Thanks in advance.
You seem to want a completely baked-in solution. Not sure I can provide that, but here's what I'd do.
Indeed use a hidden input field in a form, where the value of the field is a valid JSON string. Send the form to your server, and in your servlet use a JSON Java library to parse the JSON string.
Here json-lib, gson or Jackson would do. In your case, I'd say json-lib would seem the easiest to use.
To generate the JSON string on the client-side, either use a framework or custom solution. For instance, jQuery has a serialize() function to serialize a form's fields to a JSON object directly, which you can then convert to string. Other frameworks provide similar functions.
To learn more about JSON, be sure to read the JSON Wikipedia entry and to visit the official JSON page (which also gives you a Java implementation of the JSON data-interchange format, though maybe not the most efficient one for processing a lot of data). To make sure your generated JSON is valid, you can use JSONLint.
If the objects are simple enough, you can encode your array as a JSON string. Java has libraries to encode and decode JSON.

Categories