javajsonjson-simple

parse values from json file


I have a data.json file, the content is like this:

[
{"raw":"{\"productId\":\"PU02\",\"productType\":\"RAU\", \"productDate\":\"2022-06-03\"}"},

{"raw":"{\"productId\":\"AB03\",\"productType\":\"PUE\", \"productDate\":\"2022-05-28\"}"},
...
]

I would like to parse this json file in my gradle(java) project & transform the data to objects of following class:

public class Raw {
   private String productId;
   private String productType;
   private String productDate;

   public Raw(String productId, String productType, String productDate){
        this.productId=productId;
        this.productType=productType;
        this.productDate=productDate;
   }
}

I tried using this library in my gradle project:

// https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple
implementation 'com.googlecode.json-simple:json-simple:1.1.1'

Parsing the file (I put it under "/resource" folder):

InputStream inputStream = getClass().getClassLoader().getResourceAsStream("data.json");
JSONParser parser = new JSONParser();
try {
     JSONArray jsonArr = (JSONArray) parser.parse(new InputStreamReader(inputStream, "UTF-8"));

     Iterator iterator = jsonArr.iterator();
     while(iterator.hasNext()) {
        JSONObject jsonData = (JSONObject) iterator.next();

        // The jsonData represents each json object in the data. But how can I parse each field value out?
     }
} catch (IOException e) {
    ...
}

I get stuck how can I parse each field value out from the json data in the while loop above, also please notice there are a lot of backslashes in the data. Could someone please guide me?


Solution

  • In your JSON file, raw's value is not in JSON format, it's in String which is a JSON value of its own. In this case, you need to parse to string to JSON again.

    List<Raw> list = new ArrayList<Raw>();
    while (iterator.hasNext()) {
        JSONObject jsonData  =(JSONObject) iterator.next();
        System.out.println(jsonData.get("raw")); //delete this one 
                     
        JSONObject rawData =(JSONObject)parser.parse((String)jsonData.get("raw"));
        Raw raw = new Raw(rawData.get("productId").toString(), rawData.get("productType").toString(), rawData.get("productDate").toString());
        list.add(raw);
    }
    
    list.forEach(System.out::println);
    

    Output (added a toString method):

    Raw [productId=PU02, productType=RAU, productDate=2022-06-03]
    Raw [productId=AB03, productType=PUE, productDate=2022-05-28]