20 Mar

Android JSON Parse

Android Parsing JSON menggunakan Gson
Untuk mengambil dari dari mobile Android ke server, salah satu caranya adalah menggunakan format data “json”.

Untuk melakukan parsing JSON dari android kita bisa menggunakan pustaka tambahan bernama “Gson”
Bisa diunduh dari: http://code.google.com/p/google-gson/

Cara menggunakannya pun cukup mudah, mari kita lihat contoh berikut ini:

(Serialization)

Gson gson = new Gson();
gson.toJson(1);            ==> prints 1
gson.toJson("abcd");       ==> prints "abcd"
gson.toJson(new Long(10)); ==> prints 10
int[] values = { 1 };
gson.toJson(values);       ==> prints [1]

(Deserialization)

int one = gson.fromJson("1", int.class);
Integer one = gson.fromJson("1", Integer.class);
Long one = gson.fromJson("1", Long.class);
Boolean false = gson.fromJson("false", Boolean.class);
String str = gson.fromJson("\"abc\"", String.class);
String anotherStr = gson.fromJson("[\"abc\"]", String.class)

One thought on “Android JSON Parse

  1. Hi DaniloThe problem is that priformeng agson.fromJson(br, ArrayList.class)wont’s work, as the ArrayList.class just returns ArrayList.I know two solutions:a) Instantiate the objectArrayList doList=new ArrayList;doList=gson.fromJson theString, doList.class ;But I don’t like it too much as instatiating has a costb) create your list class:First create a class for the listpublic class DataObjects extends ArrayList {}And then use this class:DataObjects objects;objects=gson.fromJson theString, DataObjects.class ;I think this method makes clearer code and it’s useful if you new more methods in the collection (like search or classification functionalities)There is a third method using a TypeToken, but I never use it and I don’t remember how it works. If anybody could help on it

Leave a Reply

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