-1

I'm trying to read from a json file to a reader in order to parse it into a java object:`

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class main {

    public static void main(String[] args) throws IOException{

        try(Reader reader = new InputStreamReader(main.class.getResourceAsStream(
               "/Users/edwardk/IdeaProjects/practice_json/small_incidents.json"),"UTF-8")){
            Gson gson = new GsonBuilder().create();
            Person p = gson.fromJson(reader, Person.class);
            System.out.println(p);
        }
    }
}

`

Im getting a NullPointerException on run.

user85421
  • 28,957
  • 10
  • 64
  • 87
ksilla
  • 101
  • 10
  • 1
    getResourceAsStream() gets a resource, from the classpath. To read a file, from the file system, use a FileInputStream. – JB Nizet Jul 03 '17 at 18:59

2 Answers2

1

Resources are not files, and that path /Users/edwardk/... looks like a file path.

You should use the Files API to read from a file, and if you're on Windows your path will need to start with C:/, not /. If you intended to load the file as a reasource you should use a path to the file relative to your classpath. For example if the practice_json directory is on your classpath you may just need to use "small_incidents.json".

dimo414
  • 47,227
  • 18
  • 148
  • 244
1

Your code is good, but NullPointerException arises because

main.class.getResourceAsStream(
               "/Users/edwardk/IdeaProjects/practice_json/small_incidents.json"),"UTF-8")

returns null. Try to paste json file into same directory as main.java and change :

main.class.getResourceAsStream(
               "small_incidents.json"),"UTF-8")

Or specify correct relative path to small_ingredients.json

Jay Smith
  • 2,331
  • 3
  • 16
  • 27
  • This was indeed the problem, I've resolved it by moving the json file to the Recourses directory. – ksilla Jul 03 '17 at 19:55