Saleh Abusalah
Saleh Abusalah

Reputation: 53

Gson.json() returns null when parsing json file

I am trying to parse JSON file (that I have already created) to java objects.

i have tried to use JsonReader and bufferedReader but every attempt returns null

public class Sheep implements Serializable {

    @SerializedName("localId")
    @Expose
    private int localId;
    @SerializedName("globalId")
    @Expose
    private int globalId;
    @SerializedName("birthDate")
    @Expose
    private Date birthDate = null;
    @SerializedName("sellingDate")
    @Expose
    private Date sellingDate = null;
    @SerializedName("deathDate")
    @Expose
    private Date deathDate = null;
    @SerializedName("lastpregnancyDate")
    @Expose
    private Date lastpregnancyDate = null;
    @SerializedName("lastDoctorCheck")
    @Expose
    private Date lastDoctorCheck = null;
    @SerializedName("alive")
    @Expose
    private boolean alive;
    @SerializedName("sold")
    @Expose
    private boolean sold;
    @SerializedName("pregnant")
    @Expose
    private boolean pregnant;
    @SerializedName("mother")
    @Expose
    private int mother;
    @SerializedName("father")
    @Expose
    private int father;
    @SerializedName("husband")
    @Expose
    private int husband;
    @SerializedName("allDoctorChecks")
    @Expose
    private List<Date> allDoctorChecks = null;
    @SerializedName("allpregnancies")
    @Expose
    private List<Date> allpregnancies = null;
    @SerializedName("children")
    @Expose
    private List<Integer> children = null;
    @SerializedName("allHusbands")
    @Expose
    private List<Integer> allHusbands = null;
}

public class Farm implements Serializable {

    @SerializedName("allSheeps")
    @Expose
    private List<Sheep> allSheeps;
}

here you can see the two ways that I have tried to parse the JSON. actually, I don't know exactly the difference between the two, I just saw the second one in someone's answer on a similar question

1.

public class DataBase {
    private static Farm farm;

public static void main(String[] args){
        ...

    Gson gson = new Gson();
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader("farm.json"));
        Farm parsedFarm = gson.fromJson(br, Farm.class);
        System.out.println(parsedFarm);
    }catch(Exception e){
            System.out.println(e.fillInStackTrace());
    }
        ...

}

2.

public class DataBase {
    private static Farm farm;

public static void main(String[] args){
        ...

    Gson gson = new Gson();
    JsonReader jsonReader = null;
    Type farmType = new TypeToken<List<Sheep>>(){}.getType();
    try {
        jsonReader = new JsonReader(new FileReader("farm.json"));
        List<Sheep> parsedFarm = gson.fromJson(jsonReader , farmType);        
        System.out.println(parsedFarm);
    }catch(Exception e){
            System.out.println(e.fillInStackTrace());
    }
        ...

}

at the end of the parsing on both of the approaches I get :

java.lang.NullPointerException


{
  "allSheeps": [
    {
      "localId": 0,
      "globalId": 10,
      "birthDate": "Jan 12, 3913, 12:00:00 AM",
      "alive": true,
      "sold": false,
      "pregnant": false,
      "mother": -1,
      "father": -1,
      "husband": -1
    },
    {
      "localId": 1,
      "globalId": 20,
      "birthDate": "Jan 12, 3913, 12:00:00 AM",
      "alive": true,
      "sold": false,
      "pregnant": false,
      "mother": -1,
      "father": -1,
      "husband": -1
    },
    {
      "localId": 2,
      "globalId": 200,
      "birthDate": "Jan 12, 3913, 12:00:00 AM",
      "alive": true,
      "sold": false,
      "pregnant": false,
      "mother": 0,
      "father": 1,
      "husband": -1
    },
    {
      "localId": 3,
      "globalId": 300,
      "birthDate": "Jan 12, 3913, 12:00:00 AM",
      "alive": true,
      "sold": false,
      "pregnant": false,
      "mother": 1,
      "father": 2,
      "husband": -1
    },
    {
      "localId": 4,
      "globalId": 400,
      "birthDate": "Jan 12, 3913, 12:00:00 AM",
      "alive": true,
      "sold": false,
      "pregnant": false,
      "mother": 3,
      "father": 3,
      "husband": -1
    }
  ]
}

the full stacetrace:


"C:\Program Files\Java\jdk-12.0.1\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2019.1.2\lib\idea_rt.jar=49271:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2019.1.2\bin" -Dfile.encoding=UTF-8 -classpath C:\Users\saleh\Desktop\farm\out\production\farm;C:\Users\saleh\.m2\repository\com\google\code\gson\gson\2.8.5\gson-2.8.5.jar com.company.DB.DataBase
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.google.gson.internal.reflect.UnsafeReflectionAccessor (file:/C:/Users/saleh/.m2/repository/com/google/code/gson/gson/2.8.5/gson-2.8.5.jar) to field java.text.SimpleDateFormat.serialVersionOnStream
WARNING: Please consider reporting this to the maintainers of com.google.gson.internal.reflect.UnsafeReflectionAccessor
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
Exception in thread "main" java.lang.NullPointerException
    at com.company.Farm.Sheep.toString(Sheep.java:237)
    at java.base/java.lang.String.valueOf(String.java:3042)
    at java.base/java.lang.StringBuilder.append(StringBuilder.java:168)
    at java.base/java.util.AbstractCollection.toString(AbstractCollection.java:473)
    at java.base/java.lang.String.valueOf(String.java:3042)
    at java.base/java.lang.StringBuilder.append(StringBuilder.java:168)
    at com.company.Farm.Farm.toString(Farm.java:60)
    at java.base/java.lang.String.valueOf(String.java:3042)
    at java.base/java.io.PrintStream.println(PrintStream.java:897)
    at com.company.DB.DataBase.main(DataBase.java:66)

Process finished with exit code 1

Upvotes: 2

Views: 1188

Answers (1)

Anjana
Anjana

Reputation: 933

Well in both the approaches you have only initialized the file reading object but has not started to read from it.

In approach 1, if you want to read the file you should use something like below.

String line = null;
while((line = br.readLine()) != null) {
   System.out.println(line);
}

Then you have to parse the string line. In your case, actually there is nothing read from file to parse, which is why it returns a null exception. Anyhow, i can not guarantee on this approach, whether you can use Gson parse, since it reads line by line but not Json node at once.

Second approach would therefore more convenient to use where you have repeated the same mistake again as above. Refer the link attached(Gson - JsonReader Doc) to get a better understanding on approach 2.

Edit: Below mentions an example code snippet related to the 2nd approach of the original question which is extracted from the link above in any case if it may not function anymore.

String json = "{\"brand\" : \"Toyota\", \"doors\" : 5}";

JsonReader jsonReader = new JsonReader(new StringReader(json));

try {
    while(jsonReader.hasNext()){
        JsonToken nextToken = jsonReader.peek();
        System.out.println(nextToken);

        if(JsonToken.BEGIN_OBJECT.equals(nextToken)){

            jsonReader.beginObject();

        } else if(JsonToken.NAME.equals(nextToken)){

            String name  =  jsonReader.nextName();
            System.out.println(name);

        } else if(JsonToken.STRING.equals(nextToken)){

            String value =  jsonReader.nextString();
            System.out.println(value);

        } else if(JsonToken.NUMBER.equals(nextToken)){

            long value =  jsonReader.nextLong();
            System.out.println(value);

        }
    }
} catch (IOException e) {
    e.printStackTrace();
}

Upvotes: 1

Related Questions