JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. These properties make JSON an ideal data-interchange language. While working in java, i found Google-gson library to be very useful .

From the official site:

Gson is a Java library that can be used to convert Java Objects into their JSON representation.It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. There are a few open-source projects that can convert Java objects to JSON. However, most of them require that you place Java annotations in your classes something that you can not do if you do not have access to the source-code. Most also do not fully support the use of Java Generics. Gson considers both of these as very important design goals.

During my project i was having trouble converting list of json objects into list of corresponding java objects. This is how i finally did it :

 


String json1 = "[{\"contactName\":\"3\",\"contactNumber\":\"3\"},{\"contactName\":\"4\",\"contactNumber\":\"4\"}]";

JsonElement json = new JsonParser().parse(json1);

JsonArray array= json.getAsJsonArray();

Iterator iterator = array.iterator();

List<ContactDetail> details = new ArrayList<ContactDetail>();

while(iterator.hasNext()){
    JsonElement json2 = (JsonElement)iterator.next();
    Gson gson = new Gson();
    ContactDetail contact = gson.fromJson(json2, ContactDetail.class);
    //can set some values in contact, if required 
    details.add(contact);
}

Here ContactDetail class consists of String contactName and String contactNumber and their corresponding getters and setters.

Do leave a comment, in case there is any better way to do this. :)

As suggested by Gobs in the comments, another way to do it is

Gson gson = new Gson();
Type collectionType = new TypeToken<List<ContactDetail>>(){}.getType();
List<ContactDetail> details = gson.fromJson(json1, collectionType);

But I did it the other way coz I also wanted to set some values in that object.

 

About these ads