Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"}}
";

    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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...