Easy JSON parsing in Android

Here’s a very easy and fast way of parsing JSON I’ve been using the past few months: Jackson. It’s not Android-based, so you can use it on server or desktop applications as well, but I found it very useful on mobile because of the large amounts of data that resides in the cloud lately.

Enough with the chit-chat, here is an example. Let’s take this simple json string:

{
  "name" : { "first" : "Joe", "last" : "Sixpack" },
  "gender" : "MALE",
  "verified" : false,
  "userImage" : "Rm9vYmFyIQ=="
}

And this very simple Java class:

public class User {
    public enum Gender { MALE, FEMALE };

    public static class Name {
      private String _first, _last;

      public String getFirst() { return _first; }
      public String getLast() { return _last; }

      public void setFirst(String s) { _first = s; }
      public void setLast(String s) { _last = s; }
    }

    private Gender _gender;
    private Name _name;
    private boolean _isVerified;
    private byte[] _userImage;

    public Name getName() { return _name; }
    public boolean isVerified() { return _isVerified; }
    public Gender getGender() { return _gender; }
    public byte[] getUserImage() { return _userImage; }

    public void setName(Name n) { _name = n; }
    public void setVerified(boolean b) { _isVerified = b; }
    public void setGender(Gender g) { _gender = g; }
    public void setUserImage(byte[] b) { _userImage = b; }
}

After downloading and importing the Jackson libraries, you can turn that Json string into a User object:

ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
User user = mapper.readValue(new File("user.json"), User.class);

Simple, right?

Passing it a data source (File, InputStream, etc..) instead of a plain old String will cause the parser to parse the Json similar to SAX parsing, which is very fast.

For XML files, we’ll just have to parse them the old-fashion way. :-)

2 Responses to Easy JSON parsing in Android

  1. Hung says:

    Helpful material! I have been previously seeking something such as this for a while now. Many thanks!

  2. It is actually difficult to find practiced persons for this matter, nevertheless, you seem like you know what you are writing on! Regards

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Switch to our mobile site