[英]Unable To Read JSON From File
Below error while reading JSON from file从文件中读取 JSON 时出现以下错误
"Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING
at line 1 column 1 path $
at com.google.gson.Gson.fromJson(Gson.java:826)
at com.google.gson.Gson.fromJson(Gson.java:779)
at com.google.gson.Gson.fromJson(Gson.java:728)
at resources.ReadJsonFile.getjsondata(ReadJsonFile.java:50)
at resources.ReadJsonFile.main(ReadJsonFile.java:30)
Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $
at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:350)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:79)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60)
at com.google.gson.Gson.fromJson(Gson.java:814)
... 4 more"
Below is my code下面是我的代码
public class ReadJsonFile < T > {
public static void main(String[] args) {
ReadJsonFile read = new ReadJsonFile();
read.getjsondata("src/test/resource/testdataresource/addplacerequest.json",
Addbook.class);
}
public List < T > getjsondata(String filepath, Class < T > typeofT) {
//filepath= "src/test/resource/testdataresource/addplacerequest.json";
Gson gson = new Gson();;
BufferedReader bufferReader = null;
try {
bufferReader = new BufferedReader(new FileReader(filepath));
Type ListType = new TypeToken < ArrayList < T >> () {}.getType();
/
List < T > arraylist = gson.fromJson(filepath, ListType);
Iterator iter = arraylist.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}
return (arraylist);
} catch (FileNotFoundException e) {
throw new RuntimeException("Json file not found at path : " + filepath);
} finally {
try {
if (bufferReader != null) bufferReader.close();
} catch (IOException ignore) {}
}
}
}
Pojo class:宝卓 class:
public class Addbook {
public String name;
public int isbn;
public String aisle;
public String author;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIsbn() {
return isbn;
}
public void setIsbn(int isbn) {
this.isbn = isbn;
}
public String getAisle() {
return aisle;
}
public void setAisle(String aisle) {
this.aisle = aisle;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return "Addbook [name=" + name + ",isbn=" + isbn + ",aisle=" + aisle + ",authur=" + author + "]";
}
}
JSON: JSON:
[{
"name": "The King",
"isbn": 67786,
"aisle": "hfhdh",
"author": "Biju"
},
{
"name": "The King",
"isbn": 67786,
"aisle": "hfhdh",
"author": "Biju"
}
]
A small change in code, Instead of代码中的一个小改动,而不是
List<T> arraylist = gson.fromJson(filepath, ListType);
Use利用
List<T> arraylist = gson.fromJson(bufferReader, ListType);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.