Internal working of GSON - java

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.

Related

schema.org deserialize in Java

I am trying to deserialize schema.org's objects but every time I face a wall of complexity. I'm not sure if it's my fault or no one ever did this. I tried several schema.org's item and all of them sooner or later encounter the same issue (for obvious reasons actually). The problem lies on property like "Author". For example a cooking recipe has an author. Schema.org/Recipe says that the author can be an a Person or an Organisation. Both are schema.org's objects.
Until now it's easy. I get a schema for a Recipe and pass it to jsonschema2pojo.org and obtain my classes.
Then with Gson
Gson gson = new Gson();
Recipe recipe = gson.fromJson(myString,Recipe.class);
myString is the json-ld I used to generate the Recipe classes. Once I try to download some more recipes from the web, I immediately encounter schemas where the Author is not a schema.org item, but a simple String. From this point on I am blocked. The parser is stuck, exactly like google's schemaorg-java parser.
I did read that some people modify the class to have authors as Object and then modify the getter and setters. A deserializer should be made for the whole Recipe class, but it must behave differently only for Author (and other similar Parameters.
Isn't there an easier way to deserialize schema.org in java? Am I googling wrong?
If you're using GSON you'll need to create custom deserialisers. Your best bet is to read the type of the author value and if it is a string create a custom Author POJO with the name set as the string.
You've chosen a difficult language to implement this parser. Strongly typed languages are going to have a tough time deserialising data from a loosely typed language.
On top of that schema.org isn't well defined. Plus people will screw up their schema.org markup. It's up to you to decide how you'll handle it. Do you reject all data that doesn't conform exactly to the data or do you try to coerce the data?
I'm curious what you're working on. Is it a web service?

Instantiate a new instance of GSON for every serialization?

Currently, I have a lot of occurences in my code that read as follows: result = new Gson().fromJson(someString, ResultContainer.class); Should I share the GSON object over all those places? If so, per object or static per class (potentially even superclass?)
I am asking mainly because if sharing the reference statically is fine, then why isn't the Gson object static in the first place? Unless one uses fancy custom serialization rules, the method above pretty much covers what one would want Gson to do.
According to the GSON user guide:
The Gson instance does not maintain any state while invoking Json operations. So, you are free to reuse the same object for multiple Json serialization and deserialization operations.
It's not singleton because you can configure it differently via GsonBuilder.
Sharing the Gson is fine.
You can configure a Gson using GsonBuilder therefore Gsonis not a singleton.

How to convert thrift objects to readable string and convert it back?

Sometimes, we need to create some thrift objects in unit tests. We can do it by manually create object using Java code, like:
MyObj myObj = new MyObj();
myObj.setName("???");
myObj.setAge(111);
But which is not convenient. I'm looking for a way to create objects with some readable text.
We can convert thrift objects to JSON with TSimpleJSONProtocol, and get very readable JSON string, like:
{ "name": "???", "age": 111 }
But the problem is TSimpleJSONProtocol is write only, thrift can't read it back to construct an instance of MyObj.
Although there is a TJSONProtocol which supports to serialize and deserialize, but the generated JSON is not readable, it uses a very simplified JSON format and most of the field names are missing. Not convenient to construct it in tests.
Is there any way to convert thrift objects to readable string and also can convert it back? If TSimpleJSONProtocol supports converting back, which is just what I'm looking for
The main goal of Thrift is to provide efficient serialization and RPC mechanisms. What you want is something that is - at least partially - contrary to that. Human-readable data structures and machine processing efficiency are to a good extent conflicting goals, and Thrift favors the latter over the former.
You already found out about the TSimpleJson and TJson protocols and about their pros and cons, so there is not much to add. The only thing that is left to say is this: the protocol/transport stack of Thrift is simple enough.
This simplicity makes it possible to add another protocol based on your specific needs without much or overly complicated work. One could probably even write an XML protocol (if anyone really wants such bloatware) in short time.
The only caveat, especially vis-à-vis your specific case, is the fact that Thrift needs the field ID to deserialize the data. So you either need to store them in the data, or you need some other mechanism which is able to retrieve that field ID based on the field and structure names.

What is the fastest way to deserialize JSON in 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);

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.

Categories