I have a JSON file saved on disk that looks like this:
{
"author": [
"Mario Vargas Llosa",
"Maria Duenas",
"Liviu Rebreanu",
"Liviu Rebreanu"
],
"nameBook": [
"Eroul discret",
"Iubirile croitoresei",
"Ion",
"Ion"
],
"priceBook": [
34,
28,
40,
40
],
"publisherBook": [
"Humanitas",
"Polirom",
"Humanitas",
"Dacia"
],
"idBook": [
1,
2,
3,
4
]
}
Then I have the following Java code:
// read the json file
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
// get a String from the JSON object
JSONArray idBookJ = (JSONArray) jsonObject.get("idBook");
JSONArray nameBookJ = (JSONArray) jsonObject.get("nameBook");
JSONArray authorJ = (JSONArray) jsonObject.get("author");
JSONArray publisherBookJ = (JSONArray) jsonObject.get("publisherBook");
JSONArray priceBookJ = (JSONArray) jsonObject.get("priceBook");
Now I need to sort the content from the publisherBook
tag alphabetically, after the first letter of the word, using Bubble Sort. I know this isn't the most amazing programming challenge, but I got stuck at treating the strings from the JSONArray as... Strings.
This solution worked for me, but I will still post the code just in case. It is not pure Bubble Sort, but it's better than almost nothing.
The JSON array:
[
{
"firstName":"John",
"lastName":"Doe"
},
{
"firstName":"Anna",
"lastName":"Smith"
},
{
"firstName":"Peter",
"lastName":"Jones"
}
]
The JSON Simple library is available here:
package com.iglooworks.test;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
public class JsonSorter {
public static JSONArray sortJsonByKey(JSONArray json, String key)
{
JSONArray sorted = new JSONArray();
SortedMap map = new TreeMap();
for (Object o : json) {
JSONObject tmp = (JSONObject) o;
map.put(tmp.get(key),tmp);
}
Set<String> numbers = map.keySet();
for (String number : numbers) {
sorted.add(map.get(number));
}
return sorted;
}
}
The usage seems to be very simple:
package com.iglooworks.test;
import com.iglooworks.tools.JsonSorter;
import org.json.simple.*;
public class Test {
public static void main(String[] args) {
String json = "[\n" +
" {\n" +
" \"firstName\":\"John\",\n" +
" \"lastName\":\"Doe\"\n" +
" },\n" +
" {\n" +
" \"firstName\":\"Anna\",\n" +
" \"lastName\":\"Smith\"\n" +
" },\n" +
" {\n" +
" \"firstName\":\"Peter\",\n" +
" \"lastName\":\"Jones\"\n" +
" }\n" +
"]";
JSONArray jsonArray;
try {
jsonArray = tools.sortJsonByKey((JSONArray) JSONValue.parse(json), "firstName");
for (Object o : jsonArray) {
JSONObject tmp = (JSONObject) o;
System.out.println(tmp.get("firstName") + " - " + tmp.get("lastName"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Final thought: I discovered this solution may lead to NullPointerException, so I will try to improve it when I have time.