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).
Related
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?
What is the easiest to use JSON Java library to parse a JSON (It's structure may vary so I can't mapp it to a Java class as I seen multiple libraries do it) update some elements in an array in this JSON and then save it back to disk?
There are so many libraries for JSON in Java (Gson, Jackson, etc.) and so complex that seem like a total overkill for what i need as opposed to other programming languages.
What's the most straightforward one to use? (that maybe also has a few examples on how to do this)
I have had great success with Json-Simple.
You can check it out here.
I used it to parse 1.5 Million Twitter Streaming data (which is in JSON).
You may find some sample code here on my blog.
You can use java-json jar. The docs for this jar can be found here
I use net.sf.json to do this.
here is an example :
String fromFile="{\"he\",\"hello\"}" //read from file instead
JSONObject object=(JSONObject)JSONSerializer.toJSON( fromFile );
object.put("he", "hello2");
System.out.println(object);
output:
{"he":"hello2"}
I have the following String code and I want to convert to json and iterate through items and put them into an arraylist in Java.
I also have a class called Users whith its attributes and getters/setters(id, nick, age, online, avatar)how should i do:
code:
//this is the real code
String a = "{"id":"1","nick":"jhon","age":20,"online":1,"avatar":"http:\/\/www.example.com\/image.jpeg"},{"id":"2","nick":"mike","age":45,"online":0,"avatar":"http:\/\/www.example.com\/image.jpeg"},{"id":"3","nick":"carl","age":12,"online":1,"avatar":"http:\/\/www.example.com/image.jpeg"},{"id":"4","nick":"ana","age":22,"online":0,"avatar":"http:\/\/www.example.com\/image.jpeg"}";
//this is what i want to do
String a = real code sample;
Json b = a.toJson; // something like this
Arraylist<User> list = new Arraylist<User>();
for each b{
list.add( new user(b.getId(),b.getNick()....));
}
i want to do something like that and of course the code is an example and here it's not well written.
You may prefer to use Gson library which has good documentation for how to use. You can easly parse objects to JSON and JSON to object. So it may be a better alternative for your own parser.
It also supports Arrays and Collections.
I think you need to validate you array first on JSONLINT
Jackson is quite nice for this sort of thing - I've been using it for some time with no problems. I've heard nice things about Gson as well, but had no reason to switch from Jackson. Xstream also can work with Json.
Instead of working with a special "JSON" object, Jackson (and I believe Gson as well) stuff the JSON values into a POJO. You use the annotations to customize how the values are read and written.
FWIW, JSON processing is easy with a library like this, but also something you don't want to do much - it's relatively expensive in terms of CPU. It's not that the libs are slow - that kind of text processing is a lot of work.
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.
We have a Java List of objects which is marshalled via JSON which is created by Jersey.
The List is called "rows". When there is data we have:
{"records":"1","page":"1","total":"1","rows":[{"id":"692334","cell":["ECS","D","201009","","0","ABCD","11","11","","201009"]}]}
When there is no data we have:
{"page":0,"records":0,"total":0}
How can we make Jersey include the rows field even if the List has a size of 0? What we want is:
{"page":0,"records":0,"total":0,"rows":[]}
Note that we are already using a JAXB ContextResolver to ensure the JSON is correct for a single row. Not sure if we can configure this resolver to solve our problem.
Use Jackson JAX-RS provider instead of alternatives (badgerfish/jettison), which does not do XML-to-JSON conversion. Missing array is most likely due to this conversion. There are multiple ways to configure this (jersey mailing list should have a few), and latest versions may expose it directly via Jersey API.
Maybe this helps you:
http://jersey.java.net/nonav/documentation/latest/json.html#d4e903
seems that some array problems can be solved by using something like this:
JSONConfiguration.mapped().arrays("yourArrayName").build()
At least it solves the issue, when the list contains only 1 item it's also formated as an JSON array.
I managed to solve JSON array "bug" in Jersey json library. Secret ingredient is previusly mentioned JSONConfiguration and ContextResolver magic. See my following post it has a full code example, customized ContextResolver and rest Application class might be somewhat fuzzy logic in first look.
How to serialize Java primitives using Jersey REST
json array for zero or single-element Java lists
primitive integer or boolean fields without quotation chars