mercoledì 5 marzo 2014

simple JSON classes in java > Java

Json is a powerful meta-language (if I can call it this way) for storing information in form of a string. It works much like xml, but it's much faster in parsing information, it's common usage in web services, javascript and php. You can find all you need to know about json here and here. There are many json libraries in java, maybe one of the best out there is Gson by google, the only problem with gson tough is that for some really easy work it still require creating specific classes to describe the structures of the object the json string we want to parse/encode rappresents. For this reason I prefer using another java library called json-simple, even tough it requires a massive usage of downcasts. There's really nothing more I can show about this library that isn't already showed in the example page, but I can show you an easy way to iterate trough a JSONArray if you didn't figure this out already. For example let's take this json array:
            "id": "ord15",
            "colli": 1
            "id": "ord11",
            "colli": 2
Let's create a simple class that generates a list of string containing the ids specified
 private void genOrdIDList(String ordiniArrayStr) throws org.json.simple.parser.ParseException
  List list = new ArrayList();
  JSONParser parser = new JSONParser();
  JSONArray ordini  = (JSONArray) parser.parse(ordiniArrayStr);
  Iterator iter = ordini.iterator();
   JSONObject obj = (JSONObject);
   list.add((String) obj.get("id"));
  listIdOrdini= list;
With the Iterator object we get from the JSONARRAY() class we can easly access to every element of the array we are parsing. Again, more explanation and example about encoding and decoding with json-simple can be found here: I hope you now have a good time with json.