parse a string object to a JSONObject

Viewed 83

I need to parse a string that contains data of JSON file into a JSONObject and iterate over it's content to get it's keys and values for further treatement after. I'am stuck at parsing the content of a file after transforming it to a string. I tried to user parse() , quote() but it seems i'am missing a detail and i'am making a major mistake.

This is a snippet of the json file i treat :

{
    {
    "id":0,
    "name": "project1",
    "couverage": "100",
    "completness": "44.8",
    "consistency": "46",
    }
    
    {
    "id":1,
    "name": "project2",
    "couverage": "100",
    "completness": "44.8",
    "consistency": "46",
    }
    
    {
    "id":2,
    "name": "project3",
    "couverage": "100",
    "completness": "44.8",
    "consistency": "46",
    }
}

and this is the code i developed

public void readfromJsonFile(File jsonFile, long readTimeStamp) {
    logger.info("Read from JSON file:  {}", jsonFile.getName());
    
    try{
            
        //Read File Content
        String content = new String(Files.readAllBytes(jsonFile.toPath()));
        
        JSONParser jsonParser = new JSONParser(content);
        JSONObject obj = (JSONObject) jsonParser.parse();
        JSONArray key = obj.names();
        
        for (int i = 0; i < key.length (); ++i) {
            String keys = key.getString(i);
            System.out.println(keys);
            String value = obj.getString (keys);
            System.out.println(value);
    }catch (Exception e) {
            logger.error("Failed to parse JSON File: {}", jsonFile.getName());
        }
}

2 Answers

You can use Jackson Databind as well.

Create a POJO class. For example :

public class POJO {

   private int id;
   private String name;
   private String couverage;
   private String completness;
   private String consistency;

   // getters, setters and constructors

}

Modify the JSON in the file.

[
    {
    "id":0,
    "name": "project1",
    "couverage": "100",
    "completness": "44.8",
    "consistency": "46"
    },
    {
    "id":1,
    "name": "project2",
    "couverage": "100",
    "completness": "44.8",
    "consistency": "46"
    },
    {
    "id":2,
    "name": "project3",
    "couverage": "100",
    "completness": "44.8",
    "consistency": "46"
    }
]

Code :

public void readfromJsonFile(File jsonFile, long readTimeStamp) {
    logger.info("Read from JSON file:  {}", jsonFile.getName());
    try {
        ObjectMapper objectMapper = new ObjectMapper();
        POJO[] pojos = objectMapper.readValue(jsonFile, POJO[].class);
        for (int i = 0; i < pojos.length; ++i) {
            System.out.println(pojos[i].getId());
        }
    } catch (Exception e) {
            logger.error("Failed to parse JSON File: {}", jsonFile.getName());
    }
}

Try it like this

JSONArray array_= new JSONArray(content);
JSONObject obj = (JSONObject) array_.get(0);// or any index

then you can use the Object.

Related