What is the fastest way to deserialize JSON in java - java

I'm wondering what is the fastest way to parse json in JAVA ?
Getting a default object graph using the library built in Array, and Object objects
Getting a custom object graph using your own java bean
Thanks

Well, The newest and wickedly Fastest one is Boon Json. I used it in my project and got an improvement of 20X. I actually got scared and double checked to see if Library is functionally correct. Thankfully, it is :) :)
Boon has built in methods to serialize and de-serialize from/to Java Array/Maps and Custom Beans.
More Here : https://github.com/RichardHightower/boon

Mapping parsed JSON to Java bean involves additional steps, so using the raw interface (e.g. the streaming API of Jackson) will be faster. This way, you can also read until have what you need and stop parsing.
In response to #sikorski
From Jackson Wiki:
Data binding is built using Streaming API as the underlying JSON
reading/writing system: as such it has high-performance [...], but has
some additional overhead compared to pure streaming/incremental
processing
This is pretty much inevitable. If you are writing a generic Jackson parser, you obviously can't use custom types in it. Therefore it follows that you'll have to construct the custom type after you read the JSON with the generic parser, and hence the generic parser will be faster. It's worth noting though that such overhead is very small and almost never something you need to optimize away.

You can use json-simple its a high performance library and its very easy to use :
JSONParser parser=new JSONParser();
System.out.println("=======decode=======");
String s="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
Object obj=parser.parse(s);
JSONArray array=(JSONArray)obj;
System.out.println("======the 2nd element of array======");
System.out.println(array.get(1));
System.out.println();
JSONObject obj2=(JSONObject)array.get(1);
System.out.println("======field \"1\"==========");
System.out.println(obj2.get("1"));
s="{}";
obj=parser.parse(s);
System.out.println(obj);
s="[5,]";
obj=parser.parse(s);
System.out.println(obj);
s="[5,,2]";
obj=parser.parse(s);
System.out.println(obj);

Related

How to parse a JSON object, update it in place and then save it back to disk in Java?

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"}

Should I use JSONReader for complex json streams?

I've been trying to parse a very complex JSON blob with several levels of nesting. The structure of the JSON returned by the server can change for every call.
I have written a recursive JSON parser using org.json, but the performance isn't great. I do know that JSONReader offers better performance and have been trying to write a module that parses this complex JSON recursively using JSONReader.
From what I see, JSONReader is better for streams where the structure of the JSON is known. Is it advisable to use this for JSON that can change continuously? The example in the Android docs (and other examples i found online) assumes that the JSON has a fixed structure.

Internal working of GSON

I am working with GSON in my current project, i am amazed to see its power and was wondering how did it work internally. How can a GSON object change the any object into JSON and vice versa. I did read the google user guide but the internal working is not mentioned their. Can anyone explain. Also this question might not appeal some people but i am new to android programming and was exploring things. Although i used gson successfully. But i do like to know its working methodology. Can any one explain.
Thanks a lot.
Gson's internals are built on three core types:
JsonReader reads the elements in a JSON document from a stream.
JsonWriter writes the elements in a JSON document to a stream.
TypeAdapter converts a single JSON element to a single object, or vice versa.
One key pattern is that TypeAdapter is implemented recursively. For example, the TypeAdapter<FoodDelivery> may delegate to a TypeAdapter<Address> and a TypeAdapter<MenuItem>. The TypeAdapterFactory interface makes it easy to build type adapters for arbitrary types.
One other key pattern is that Gson includes some awesome type adapters built-in by default. There's type adapters for primitives, strings, collections. Plus a special type adapter that takes an arbitrary Java class and converts it to a JSON object field-by-field.
I suggest that you do not perform recreation of objects and not force GSON except where it is needed. IMO, you have to use GSON anywhere where you have REST service, but GSON is more slower than java collections (ArrayList or HashMap or any other ...) and you will decrease app performances if you continue to use GSON everywhere.
Second reason is that when you perform object recreation, this is done in phone memory, and just for example, I had a problem with JSON (GSON) object which was exposed over service because it was 35-40MB and object creation uses over 70MB of RAM. There I had OutOfMemoryException, MemoryExhaustedException and more problems this kind.
If this limitations are not interested for you (you don't have large objects, or high speed is not required), then proceed to convert objects to GSON.

Create Object vs Reading Json

I'm working on an Android app. The app gets the data as JSON string (name of universities and student lists) and manipulate the app according to the data.
What will be a better approach?
Create a new Object and parse the JSON string into it, and work with the object, or
Keep the JSON string, and just use JSONObject whenever I need to grab information from the string
Or any other way?
If I'm using the new Object, how can I transfer (or share) the object with other activities in the app?
I know that for string we can use putextra().
Use objects.
I would suggest to use Jackson library,
be cause it is very fast and easy to ingrate.
You can find code examples here :
http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
P.S. : Jackson is not the only library for this approach > Jackson Vs. Gson
I almost always parse the JsonObject into a specific object E.g. class University.
One benefit of doing this, is you can put it nicely into collections. E.g. HashMaps, Set or just straight List. When dealing with it as a JsonObject you won't be able to as easily work with it.
You can do things like sort it if you Object inherits Comparable, and can define equals/toString/hashCode.
There are a number of other benefits, but I think you'll find holding that data in a real data structure will give you the most benefit
I would recommend parsing the string (or using a library to do this for you!) and filling an object. This way, your model object can control the data and how it is shared with other objects, and use internal data structures to optimize usage. If you stuck with the JSON string you'd end up parsing it multiple times to pull out data.
However you decide to share the object/string across activities shouldn't affect your decision for how to model the data. You'll likely end up passing it across activities in any case.
I suggest that you use objects too.
You can use Gson library to do any conversion between json string and objects. It is very, very easy to use. http://code.google.com/p/google-gson/
To transfer the data between other activities you can make your object implement the Serializable interface, this way you can use the .putExtra() and pass it forward.

How one can represent the JSON Object in clean POJO?

I'm very new to Java. I'm just parsing a string and getting the Json Response like this:
{
"customer_id": "user",
"merchantId": "xxxx",
"cards":
[
{
"card_token": "715fc10a-e7b3-48a1-b6e7-09e71ac050f8",
"card_number": "11111111",
"card_isin": "23232",
"card_exp_year": "2013",
"card_exp_month": "12"
}
]
}
For some reason I wish I could be able to represent this in a POJO. Note that the cards field can consist of more than 1 field.
I'm new to Java. I don't want the code for doing it, but I want to know what is the best way to represent these structure in POJO.
You can use GSON that can easily convert json to java object (generic) and vice versa which further you can use for your POJO.
- Manual parsing of JSON to object will be a pain.
- Its better to go with Jackson, which i use.
- Or you can also choose GSON (created by google for its internal use initially).
See this link for implementation example:
http://www.mkyong.com/java/json-simple-example-read-and-write-json/
The two dominate JSON processors for Java are GSON (as #Abu points out in his answer) and Jackson. These libraries will help you map a Java POJO to a JSON object, and vice-versa.
Here is a comparison on SO.
You can also use Jackson JSON. It's a bit faster and it works great with the Java API for RESTful Services (JAX-RS), the Java standarization for REST api's.
Here's a better comparison between the two: Jackson Vs. Gson
To read an object from String, checkout the ObjectMapper class.

Categories