How to convert a Json file to a list of objects in Java?

0

I'm trying to read the data from a .json file and store it in a% of objects%, however an error is occurring that I do not know what it means.

Class Sale - To store the data that will be brought from the file

public class Sale {

private int n_payments;
private String sale_id;
private String timestamp;
private String payment_method;
private String id_product;

public int getN_payments() {
        return n_payments;
}
public void setN_payments(int n_payments) {
        this.n_payments = n_payments;
}
public String getSale_id() {
        return sale_id;
}
public void setSale_id(String sale_id) {
        this.sale_id = sale_id;
}
public String getTimestamp() {
        return timestamp;
}
public void setTimestamp(String timestamp) {
        this.timestamp = timestamp;
}
public String getPayment_method() {
        return payment_method;
}
public void setPayment_method(String payment_method) {
        this.payment_method = payment_method;
}
public String getId_product() {
        return id_product;
}
public void setId_product(String id_product) {
        this.id_product = id_product;
}
}

JSONRead class- To read the data

public class JSONRead {

public static void main(String[] args) {
    Gson gson = new Gson();
    java.lang.reflect.Type type = new TypeToken<List<Sale>>() {}.getType();
    try{
        Reader br = new FileReader(new File(ClassLoader.getSystemResource("C:\Users\casa\Desktop\sales.jsonl").getFile()));

        List<Sale> sales = gson.fromJson(br, type);

        System.out.println(sales);
    }catch(IOException e){
        e.printStackTrace();
    }
}
}

Error that is shown

Exception in thread "main" java.lang.NullPointerException
at JSONRead.main(JSONRead.java:18)
C:\Users\casa\AppData\Local\NetBeans\Cache.2\executor-snippets\run.xml:53: Java returned: 1
FALHA NA CONSTRUÇÃO (tempo total: 4 segundos)

Sales.json file

{"n_payments":1,"sale_id":"574936432081248","timestamp":"2017-03-03 11:51:42","payment_method":"debit","product_id":"2700455360785340"}
{"n_payments":1,"sale_id":"8390335018619568","timestamp":"2017-11-19 22:00:19","payment_method":"debit","product_id":"0157148090593854"}
{"n_payments":1,"sale_id":"6734916500594364","timestamp":"2017-03-11 0:26:28","payment_method":"credit","product_id":"4995839903495816"}
    
asked by anonymous 18.03.2018 / 21:28

1 answer

1

I would do something like this:

FileInputStream fstream = new FileInputStream("C:\Users\casa\Desktop\sales.jsonl");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));


Gson gson = new Gson();
List<Sale> sales = new ArrayList<>();

String strLine;
while ((strLine = br.readLine()) != null)   {
  sales.add(gson.fromJson(strLine, Sale.class));
}

br.close();
    
19.03.2018 / 02:23