解析json文件时,Gson.json()返回null

时间:2019-08-01 13:04:19

标签: java json gson

我正在尝试将JSON文件(已经创建)解析为java对象。

我尝试使用JsonReader和bufferedReader,但是每次尝试都返回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;
}

,在这里您可以看到我尝试解析JSON的两种方法。实际上,我不确切知道两者之间的区别,我只是在某人针对类似问题的答案中看到了第二个问题

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());
    }
        ...

}

在我得到的两种方法的解析结束时:

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
    }
  ]
}

完整的跟踪记录:


"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

1 个答案:

答案 0 :(得分:1)

在这两种方法中,您都只初始化了文件读取对象,但尚未开始从文件读取对象。

在方法1中,如果要读取文件,则应使用以下内容。

setTimeout(function() {
  this.secondFunction();
}.bind(this), 2000);

然后,您必须解析字符串 line 。在您的情况下,实际上没有从文件读取任何内容以进行解析,这就是为什么它返回空异常的原因。无论如何,我不能保证是否可以使用 Gson parse ,因为它可以逐行读取而不是 Json节点

因此,如果您再次重复上述错误,第二种方法将更方便使用。请参考附件中的链接(Gson - JsonReader Doc)以更好地理解方法2。

编辑:下面提到了与原始问题的第二种方法相关的示例代码片段,该代码片段是从上面的link中提取出来的,如果可能不再起作用,则无论如何。

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