LoganSquare parsing Android library : feedback, benchmarks, pros, cons - android

I'm using Jackson with DataBind library to parse json and map it java object. I'm also using Gson on other project where perf is less required.
On 17 Feb, LoganSquare library is first released, promising 4-10 time faster parsing as Gson.
What advantages as LoganSquare than Gson/Jackson didn't have ?
Pros and cons ?
Do you have benchmarks in production application ?
Is is stable enough for a production app?
I understand it can be a primarly opinion base question, so be as technic and specific as possible and base your answer on real data.

Well to be clear if you are releasing your app to devices with ART you will have a huge speed advantage trough parsing.
so i will explain my experience with logansquare so far.
pros :
Easy to use: with Gson you have to use Type for parsing json array to a object list, in loganSquare it is so easy as LoganSquare.parseList()
Faster : in any device (test it yourself) it is slightly faster.
FasterER: in ART devices its speed gap is really giant see their benchmark
RetroFit friendly: yeah it plays well with retrofit.
cons :
NO REALM DB : I could't make it run with Realm db so far(I didnt tried hard yet)
Custom Type Adapter :Couldn't find a type adapter or something similar so far but I am not sure.
see their benchmark here
and here is my poor benchmark results(it is not a proper benchmark but it is something):
Emulator nexus 5, with DalvikVM,4.2 jellybean
Benchmarks
Parsed model
import com.bluelinelabs.logansquare.annotation.JsonField;
import com.bluelinelabs.logansquare.annotation.JsonObject;
import com.google.gson.annotations.SerializedName;
/**
* Created by Ercan on 6/26/2015.
*/
#JsonObject(serializeNullCollectionElements = true ,serializeNullObjects = true)
public class Village {
#SerializedName("IdVillage")
#JsonField(name ="IdVillage")
String tbsVillageId;
#SerializedName("TBS_VillageId")
#JsonField(name ="TBS_VillageId")
String townRefId;
#SerializedName("VillageName")
#JsonField(name ="VillageName")
String villageName;
#SerializedName("Status")
#JsonField(name ="Status")
String status;
#SerializedName("DateInserted")
#JsonField(name ="DateInserted")
String dateInserted;
#SerializedName("DateLastModified")
#JsonField(name ="DateLastModified")
String datelastModified;
public String getTbsVillageId() {
return tbsVillageId;
}
public void setTbsVillageId(String tbsVillageId) {
this.tbsVillageId = tbsVillageId;
}
public String getTownRefId() {
return townRefId;
}
public void setTownRefId(String townRefId) {
this.townRefId = townRefId;
}
public String getVillageName() {
return villageName;
}
public void setVillageName(String villageName) {
this.villageName = villageName;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getDateInserted() {
return dateInserted;
}
public void setDateInserted(String dateInserted) {
this.dateInserted = dateInserted;
}
public String getDatelastModified() {
return datelastModified;
}
public void setDatelastModified(String datelastModified) {
this.datelastModified = datelastModified;
}
}

I have run LoganSquare Benchmark project on my Nexus 5 device with Android 6.0.1 and here is the result:
Also, after a short time spend with the lib, here are my pros and cons:
Pros
is really fast in both parsing and serialization
small library size
handy methods for lists parsing and serialization
useful converters
compile-time errors instead of run-time only
Cons
not much of a documentation, also not many questions & answers on
StackOverflow :)
not many types supported
only String keys supported in Map collections
I wrote an example project to see how LoganSquare works and also a blog post, so take a look there for more information.

response.body() it is string json response
// MovieData it is a model Class
MovieData movieData=LoganSquare.parse(response.body(),MovieData.class);
Log.d("onResponse: ",movieData.getTitle());

The library is not updated since 4+ years.
It was working mostly fine till now but according to my knowledge it will stop working after gradle 5.

Related

Android: Handle different type of value with GSON

In my app, I get and parse a JSON stream from a wordpress (RESP API v2) website.
I use, OKHTTP, RETROFIT with GSON converter to read and parse the stream into my objects.
Usually, my GSON converter expect an object but, because of a recent update, the website gives me a boolean (false). The value isn't set yet.
This is my question: "Can I handle different type of values for the same variable name with GSON Serialize and how?"
Thank you!
This is my object:
public static class StageProfileImage {
//////////////////////////////////////////////////
// Variables
//////////////////////////////////////////////////
#SerializedName("url")
private String stageProfileImageUri;
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// Setters & Getters
//////////////////////////////////////////////////
public String getStageProfileImageUri() {
return stageProfileImageUri;
}
public void setStageProfilUri(String stageProfileImageUri) {
this.stageProfileImageUri = stageProfileImageUri;
}
/////////////////////////////////////////////
}
Important: I can't modify the stream.
try #SerializedName(value = "url", alternate = {"altkey1", "altkey2"})
Edit: Changed to a more generic example.
Thanks but it isn't my problem. In fact, GSON can't convert the stream from the website because instead of this:
"stage_profile_image" : {
...
}
My stream give me that:
"stage_profile_image" : false
In the first one, I get an object but in the second one I get a boolean which is not the type of value it expects and GSON is unable to do the convertion.

parse json android and show it in textview

I am new to android developing, my website returns posts with following format in json:
post= {
'artist':'xxxx',
'title':'xxxx',
'text':'xxxx',
'url':'http://xxxx'
}
I know something about receiving a file from the net and saving it to a SD card, but I want to do it on fly, parse it and show in on some text view, can you please give me some simple code for this?
I tried searching but I can't find a good tutorial for this, so this is the last place I'm coming to solve my problem.
A good framework for parsing XML is Google's GSON.
Basically you could deserialize your XML as follows (import statements left out):
public class Post {
private String artist, title, text, url;
public Post() {} // No args constructor.
}
public class Main {
public static void main(String[] args) {
Gson gson = new Gson();
String jsonString = readFromNetwork(); // Read JSON from network...
Post post = gson.fromJson(jsonString, Post.class);
// Use post instance populated with your JSON data.
}
}
Read more in GSON's user guide.

GSON problem in android 2.3.3

I am having trouble serializing to JSON via GSON . Here is my Poll class
package com.impact.datacontracts;
public class Poll {
public int FeedID;
public int Answer;
public Poll(){}
}
I am serializing like this
public void submitPoll(int answerID, int feedID) {
Poll poll = new Poll();
poll.Answer = answerID;
poll.FeedID = feedID;
Gson gson = new Gson();
String jsonString = gson.toJson(poll);
Toast.makeText(_context, jsonString, Toast.LENGTH_LONG).show();
}
in Android 2.2 i get Toast as:
{"FeedID":"1","Answer":"1"}
which is correct , while the same code produces this Toast in Android 2.3.3 :
{"FeedID":"0","Answer":"0"}
but if i change the datatype of FeedID and Answer to String then it works fine in 2.3.3 , i can live with Strings but what could be wrong here?
Thanks
Are you trying this out on an HTC device? If yes, you might be a victim of this. Test your app on a vanilla Android device (such as a Nexus One / S or on an emulator). If the problem disappears, you know it was the device's fault and you can easily repackage GSON by following the steps on the aforementioned page.

Using JSON to create an object in Groovy/Grails

I have a Groovy/Grails website that is being used to send data to Android clients via JSON. I have created both the Android client and the Groovy/Grails website; and they can output the same objects in JSON.
I can successfully create the respective objects in Android by mapping the JSON output to Java objects, however I was wondering if it's possible to use the JSON output to create a new domain object in Groovy/Grails? Is there a way of passing the JSON output to a controller action so that object will be created?
Here is an example of the JSON that I'd like to send;
{
"class":"org.icc.callrz.BusinessCard.BusinessCard",
"id":1,
"businessCardDesigns":[],
"emailAddrs":[
{
"class":"org.icc.callrz.BusinessCard.EmailAddress",
"id":1,
"address":"chris#krslynx.com",
"businessCard":{
"_ref":"../..",
"class":"org.icc.callrz.BusinessCard.BusinessCard"
},
"index":0,
"type":{
"enumType":"org.icc.callrz.BusinessCard.EmailAddress$EmailAddressType",
"name":"H"
}
},
{
"class":"org.icc.callrz.BusinessCard.EmailAddress",
"id":2,
"address":"cb#i-cc.cc",
"businessCard":{
"_ref":"../..",
"class":"org.icc.callrz.BusinessCard.BusinessCard"
},
"index":1,
"type":{
"enumType":"org.icc.callrz.BusinessCard.EmailAddress$EmailAddressType",
"name":"W"
}
}
]
}
The "class" matches to the Domain I'd like to save to, the ID is the ID of the Domain, then each item within the businessCardDesigns and emailAddrs needs to be saved using similar methods (in the Domain the businessCardDesigns and emailAddrs are ArrayLists). Many thanks in advance!
SOLUTION:
#RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity<String> createFromJson(#RequestBody String json) {
Owner.fromJsonToOwner(json).persist();
return new ResponseEntity<String>(HttpStatus.CREATED);
}
Using the built-in Grails JSON converter makes this easier than the other answers, in my opinion:
import grails.converters.JSON
class PersonController {
def save = {
def person = new Person(JSON.parse(params.person))
person.save(flush:true)
}
}
The other benefits are:
There's no need to muck around in any config files
The resulting JSON object can be manipulated, if necessary, before assigning properties
It's far clearer in the code what's happening (we're parsing a JSON object and setting the properties on the Person entity)
I know you already accepted an answer but if I'm reading your question right, there's a built in "Grails" way to do this.
Create an entry for your action in URLMappings.groovy and turn on request parsing. For example, I create RESTful mappings like so:
"/api/bizCard/save"(controller: "businessCard", parseRequest: true) {
action = [POST: "save"]
}
And then in you controller
def save = {
def businessCardInstance = new BusinessCard(params.businessCard)
....
businessCardInstance.save(flush:true)
}
this might work for you
http://static.springsource.org/spring-roo/reference/html/base-json.html

Is there a htmlDecode?

I am downloading a JSONObject from a web site. The entries are however HTML-encoded, using
"
and
&
tags. Is there an easy way to get these to Java strings? Short of writing the converter myself, of course.
Thanks RG
PS: I am using the stuff in a ListView. Probably I can use Html.fromHTML as I can for TextView. Don't know.
OK, I simply went to write my own quick fix. Not efficient, but that's OK for the purpose. A 5-minutes-solution.
public static String unescape (String s)
{
while (true)
{
int n=s.indexOf("&#");
if (n<0) break;
int m=s.indexOf(";",n+2);
if (m<0) break;
try
{
s=s.substring(0,n)+(char)(Integer.parseInt(s.substring(n+2,m)))+
s.substring(m+1);
}
catch (Exception e)
{
return s;
}
}
s=s.replace(""","\"");
s=s.replace("<","<");
s=s.replace(">",">");
s=s.replace("&","&");
return s;
}
I've heard of success in using the Apache Commons on Android.
You should be able to use StringEscapeUtils.unescapeHtml() (from the Lang package).
Here are the (fairly straightforward) directions on using the Apache Commons libraries in your Android apps: Importing org.apache.commons into android applications.

Categories

Resources