Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

2015-08-07

GSON makes the conversion JSON to POJO very easily


As a java developer one should know JSONObject very well. On the other hand, if one depends so heavily on JSONObject, the conversion from JSON to POJO becomes sometimes a burden if the structure of JSON string is very complex. One has to write so many codes to call JSONObject.getString("") and so on. Thanks GSON, there is a better way to convert JSON to java object.

 Define a java class to be an exact model of the JSON string like: 
{"book":{"translations":[{"translatedText":"Bonjour tout le monde"}]}} 
The java class:
class BookWrapper {
    public Book book;

    public static BookWrapper fromJson(String s) {
        return new Gson().fromJson(s, DataWrapper.class);
    }
    public String toString() {
        return new Gson().toJson(this);
    }
}
class Book {
    public List<Translation> translations;
}
class Translation { 
    public String translatedText;
}
As you can see, it's very convenient and elegant to use BookWrapper.fromJson(JsonString) to convert a JSON string to the java object.
Furthermore, GSON supports the versioning of a java object. It's helpful when the JSON structure has been changed with some versions.

Usage taken from the GSON user guide:

Versioning Support

Multiple versions of the same object can be maintained by using @Since annotation. This annotation can be used on Classes, Fields and, in a future release, Methods.  In order to leverage this feature, you must configure your Gson instance to ignore any field/object that is greater than some version number.  If no version is set on the Gson instance then it will serialize and deserialize all fields and classes regardless of the version.

public class VersionedClass {
  @Since(1.1) private final String newerField;
  
@Since(1.0) private final String newField;
  private final String field;

  public VersionedClass() {
    this.newerField = "newer";
    this.newField = "new";
    this.field = "old";
  }
}

VersionedClass versionedObject = new VersionedClass();
Gson gson = new GsonBuilder().setVersion(1.0).create();

String jsonOutput = gson.toJson(someObject);
System.out.println(jsonOutput);
System.out.println();gson = new Gson();
jsonOutput = gson.toJson(someObject);
System.out.println(jsonOutput);


======== OUTPUT ========
{"newField":"new","field":"old"}
{"newerField":"newer","newField":"new","field":"old"}


2009-10-22

HOWTO: Install Java 1.4 & 1.5 on Snow Leopard

Because of some projects, I need to complie some Java projects in Eclipse with older Java versions, such as 1.4.2, on my MacBook, but since Snow Leopard is such a new(!) operating system, it lacks a lot of support for softwares running with older versions of libraries.

After a long while searching in the internet, finally I found the way to install JVM 1.4 & 1.5 on Snow Leopard!

Java 1.4:
Here is how to get Java 1.4 running on snow leopard.
cd /tmp/
curl -o java.1.4.2-leopard.tar.gz http://tedwise.com/files/java.1.4.2-leopard.tar.gz
tar -xvzf java.1.4.2-leopard.tar.gz
sudo mv 1.4.2 /System/Library/Frameworks/JavaVM.framework/Versions/1.4.2
cd /System/Library/Frameworks/JavaVM.framework/Versions/
sudo ln -s 1.4.2 1.4
open "/Applications/Utilities/Java Preferences.app"
and Java 1.5:
cd /tmp/
curl -o java.1.5.0-leopard.tar.gz http://tedwise.com/files/java.1.5.0-leopard.tar.gz
tar -xvzf java.1.5.0-leopard.tar.gz
sudo mv 1.5.0 /System/Library/Frameworks/JavaVM.framework/Versions/1.5.0-leo
cd /System/Library/Frameworks/JavaVM.framework/Versions/
sudo rm 1.5.0
sudo mv 1.5.0-leo 1.5.0
sudo ln -s 1.5.0 1.5
open "/Applications/Utilities/Java Preferences.app"
It really works! ;-)

via [OneSwarm]

Update (2014-05-05): the broken links are fixed.

2009-06-18

How to write a Java-based HTML-Crawler?

It's actually a task from my test work. First idea that came to me is: Use an instance of XMLReader to fetch a page, then use regular expression to parse, save the results with the help of XMLWriter. Such a way seems naive, but almost non-usable! So let me explain the difficulty which can be confronted.


1. Internet is a mess.



There are too many web pages in the cyberspace that do NOT pay any attention to the web standard (X)HTML. So we can see a lot of nested tags, unpaired tags and even worse, badly programmed JavaScript may be in just one page.



2. Ads are confusing.


Now come Advertisements with different formats, e.g. Text, Flash, Images and Videos(!). Most of them live with a lot of JavaScript to improve their impact. Some use even non-standard tags such as <noscript> or browser-specific tags.


3. Ajax is not so user-friendly.

We all love to use Ajax technology. A typical Ajax use case is to let some texts loaded dynamically, then it results a severe problem with a HTML-Parser. If the parser saves the fetched HTML-page in a cache, the cache file contains a lot of JavaScript which load elements later. So with the cache file we cannot get what we want normally.


What can we do with all those?


The current popular solution is to use the HTML or Webpage validation tools! Between different libraries HTMLUnit will fit our requirement exactly. The project describes itself as a "GUI-Less browser for Java programs". So we can handle a webpage just like we see it in our browser. The above disadvantages could be then avoided.


Interesting is, HTMLUnit is originally a java unit testing framework for testing web based applications. It is similar in concept to HTTPUnit but is very different in implementation.


For beginners, HTMLUnit provides a very simple documentation to "Get Started". With the examples provided on the website it's okay to write a HTML-Crawler now.