Angelo Neves Angelo Neves - 5 months ago 8
Java Question

How to catch a string in JSON file in java?

I have a JSON file and need to get the parameter ' fulltext ' , but I'm new to JSON and do not know how to retrieve it in Java . Could someone explain to me how caught this value fulltext ?

Here a piece of the file in JSON.

{
"head": {
"vars": [ "author" , "title" , "paper" , "fulltext" ]
} ,
"results": {
"bindings": [
{
"author": { "type": "uri" , "value": "http://data.linkededucation.org/resource/lak/person/richard-scheines" } ,
"title": { "type": "literal" , "value": "Discovering Prerequisite Relationships among Knowledge Components" } ,
"paper": { "type": "uri" , "value": "http://data.linkededucation.org/resource/lak/conference/edm2014/paper/492" } ,
"fulltext": { "type": "literal" , "value": "GET TEXT" }
} ,

Answer

Json library download from here jar dowonload form here

Add this code in JSonParsing.java

   import org.json.*;
    public class JSonParsing {
        public static void main(String[] args){
            String source = "{\n" +
    "  \"head\": {\n" +
    "    \"vars\": [ \"author\" , \"title\" , \"paper\" , \"fulltext\" ]\n" +
    "  } ,\n" +
    "  \"results\": {\n" +
    "    \"bindings\": [\n" +
    "      {\n" +
    "        \"author\": { \"type\": \"uri\" , \"value\": \"http://data.linkededucation.org/resource/lak/person/richard-scheines\" } ,\n" +
    "        \"title\": { \"type\": \"literal\" , \"value\": \"Discovering Prerequisite Relationships among Knowledge Components\" } ,\n" +
    "        \"paper\": { \"type\": \"uri\" , \"value\": \"http://data.linkededucation.org/resource/lak/conference/edm2014/paper/492\" } ,\n" +
    "        \"fulltext\": { \"type\": \"literal\" , \"value\": \"GET TEXT\" }\n" +
    "      }\n" +
    "    ]\n" +
    "  }\n" +
    "}\n" +
    "";
            JSONObject main = new JSONObject(source);
            JSONObject results = main.getJSONObject("results");
            JSONArray bindings = results.getJSONArray("bindings");
            JSONObject firstObject = bindings.getJSONObject(0);
            JSONObject fulltextOfFirstObject = firstObject.getJSONObject("fulltext");
            String type = fulltextOfFirstObject.getString("type");
            String value = fulltextOfFirstObject.getString("value");
            System.out.println("Type :"+ type+"\nValue :"+value);
        }
    }

NOTE: In JSON {} represents jsonObject and [] represents jsonArray.