2

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
5
  • first approach is right one, where do you get NullPointerException? so you have getters and setters in Sheep class? Commented Aug 1, 2019 at 13:07
  • when I remove the printing line I don't get an exception so I assume that the parsing returns null Commented Aug 1, 2019 at 13:24
  • acctualy i have tried now to do the following : System.out.println(parsedFarm == null ); and it printed False so then when I tried to wrap it with ``` if(parsedFarm != null)``` it failed again and returned null Commented Aug 1, 2019 at 13:27
  • Can you add your complete stack trace please and the associated code please ? Commented Aug 1, 2019 at 13:53
  • I have added the full stacktrace. all the code needed is here and yes I have setters and getters in Farm and Sheep for every field Commented Aug 1, 2019 at 14:26

1 Answer 1

1

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();
}
Sign up to request clarification or add additional context in comments.

2 Comments

the purpose is not just printing the data. I want to use this data to change things in it and store it as anew version. to give you a better idea, the JSON file is my database. I am storing the data about the farm in this JSON file and modify it as necessary. so I am trying not just to print, i want it as a farm object for later use
Code snippet is just an example on how to read the json data with jsonReader. If you can read the data as it is, what you can do with them is not relevant to this. Simply saying, it is not specifically has to be printing. Rest is for you to think. For an example, you can simply set the values you are reading to a new farm object with setters. That is OOP 101, i guess.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.