org.json has classes to parse and write json string. It also converts between json and xml, HTTP header, Cookies, and CDF. The main classes are:
This examples shows how to parse a JSON string. The JSON string in this example is a list of genres (limited to 2) from freemusicarchive.org
package com.studytriails.json.orgjson;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
import org.json.simple.JSONArray;
public class ParseJson1 {
public static void main(String[] args) throws MalformedURLException, IOException {
String url = "http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2";
String genreJson = IOUtils.toString(new URL(url));
JSONObject json = new JSONObject(genreJson);
// get the title
System.out.println(json.get("title"));
// get the data
JSONArray genreArray = (JSONArray) json.get("dataset");
// get the first genre
JSONObject firstGenre = (JSONObject) genreArray.get(0);
System.out.println(firstGenre.get("genre_title"));
}
}
Lets look at how to build the same JSON string as above but using a bean for the genre
package com.studytriails.json.orgjson;
import org.json.JSONObject;
public class BuildJson1 {
public static void main(String[] args) {
JSONObject dataset = new JSONObject();
dataset.put("genre_id", 1);
dataset.put("genre_parent_id", JSONObject.NULL);
dataset.put("genre_title", "International");
// use the accumulate function to add to an existing value. The value
// will now be converted to a list
dataset.accumulate("genre_title", "Pop");
// append to the key
dataset.append("genre_title", "slow");
dataset.put("genre_handle", "International");
dataset.put("genre_color", "#CC3300");
// get the json array for a string
System.out.println(dataset.getJSONArray("genre_title"));
// prints ["International","Pop","slow"]
// increment a number by 1
dataset.increment("genre_id");
// quote a string allowing the json to be delivered within html
System.out.println(JSONObject.quote(dataset.toString()));
// prints
// "{\"genre_color\":\"#CC3300\",\"genre_title\":[\"International\",\"Pop\",\"slow\"],
// \"genre_handle\":\"International\",\"genre_parent_id\":null,\"genre_id\":2}"
}
}
Lets look at an example of how to use the java.json.CDL class to convert a jsonarray to a csv
package com.studytriails.json.orgjson;
import java.io.IOException;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonToCsv {
public static void main(String[] args) {
String url = "http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=10";
try {
String genreJson = IOUtils.toString(new URL(url));
JSONObject json = new JSONObject(genreJson);
System.out.println(CDL.toString(new JSONArray(json.get("dataset").toString())));
} catch (IOException e) {
e.printStackTrace();
}
}
}
(Note: This article’s original links is here )