Monday, 21 March 2016

java - Retrieving values from nested JSON Object



I've got JSON file, which I want to parse.
The JSON file ("myfile") has format as follows:



{
"LanguageLevels": {
"1": "Początkujący",

"2": "ŚrednioZaawansowany",
"3": "Zaawansowany",
"4": "Ekspert"
}
}


I want to retrieve value (ŚrednioZaawansowany) of Key 2 from Language Levels.



import java.io.FileNotFoundException;

import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonSimpleExample {
public static void main(String[] args) {


JSONParser parser = new JSONParser();

try {

Object obj = parser.parse(new FileReader("myfile");
JSONObject jsonObject = (JSONObject) obj;
JSONObject jsonChildObject = (JSONObject)jsonObject.get("LanguageLevels");



What to do next? How I can iterate over it?


Answer



Maybe you're not using the latest version of a JSON for Java Library.



json-simple has not been updated for a long time, while JSON-Java was updated 2 month ago.



JSON-Java can be found on GitHub, here is the link to its repo: https://github.com/douglascrockford/JSON-java



After switching the library, you can refer to my sample code down below:




public static void main(String[] args) {
String JSON = "{\"LanguageLevels\":{\"1\":\"Pocz\\u0105tkuj\\u0105cy\",\"2\":\"\\u015arednioZaawansowany\",\"3\":\"Zaawansowany\",\"4\":\"Ekspert\"}}\n";

JSONObject jsonObject = new JSONObject(JSON);
JSONObject getSth = jsonObject.getJSONObject("LanguageLevels");
Object level = getSth.get("2");

System.out.println(level);
}



And as JSON-Java open-sourced, you can read the code and its document, they will guide you through.



Hope that it helps.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...