Home > Enterprise >  Java get values from json file using simple json lib
Java get values from json file using simple json lib

Time:08-11

I have json file with this format

{ "1" : { "path" : ["C"] , "Des" : ["D"] } ,
"2" : { "path" : ["A"] , "Des" : ["D"] } ,
"3" : { "path" : ["C"] , "Des" : ["B"] } }

I want to get values in class objects and using this code to see result before added it to arraylist objects

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException; 
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;    
public class test2 {
    public static void main(String[] args) {
        JSONParser parser = new JSONParser();
        
        try {
            Object obj = parser.parse(new FileReader("C:/Users/dell/Desktop/streams.json"));
            JSONObject jsonObject = (JSONObject) obj;
            JSONObject json0 = (JSONObject) jsonObject.get(0);
             System.out.println(json0);
  
        }
        catch (FileNotFoundException  e) { e.printStackTrace();}
        catch (IOException  e) { e.printStackTrace();}
        catch (ParseException  e) { e.printStackTrace();}
        catch (Exception  e) { e.printStackTrace();}
        }
        }

CodePudding user response:

The problem is jsonObject is not array, try to do this:

jsonObject.get("1")

Instead of this:

jsonObject.get(0)

CodePudding user response:

To get all keys of the json object simply do:

jsonObject.keySet()

If you want to put keys to the list:

List<String> keys = new ArrayList<>((Set<String>) jsonObject.keySet());
  • Related