使用 gson 加载 JSON
loading JSON with gson
尝试加载 JSON 文件时出现错误,但这是什么意思?
public class MovieCollection{
private List<Movie> movies;
private Movie movie;
public MovieCollection() {
this.movies = new ArrayList<Movie>();
}
/**
* Creates a new book collection with the specified list of books pre-defined.
*
* @param books A books list.
*/
public MovieCollection(List<Movie> movies) {
this.movies= movies;
}
public static MovieCollection loadFromJSONFile (File file){
Gson gson = new Gson();
JsonReader jsonReader = null;
try {
jsonReader = new JsonReader(new FileReader(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("Error");
}
return gson.fromJson(jsonReader, MovieCollection.class);
}
预期 BEGIN_OBJECT 但 BEGIN_ARRAY 在第 1 行第 2 列路径 $
该错误清楚地表明您要读取的文本实际上是一个数组,而不是 JSON。它是一个 JSON 的数组。这意味着您需要某种方式来读取对象数组,如下所示:
Gson gson = new Gson();
User[] userArray = gson.fromJson(userJson, User[].class);
这允许您从 json 数组文本中读取用户对象数组。上面代码的示例 json 包含在下面。
[
{
"name": "Alex",
"id": 1
},
{
"name": "Brian",
"id": 2
},
{
"name": "Charles",
"id": 3
}
]
用户 class 定义为
public class User
{
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
此处提供参考 link
尝试加载 JSON 文件时出现错误,但这是什么意思?
public class MovieCollection{
private List<Movie> movies;
private Movie movie;
public MovieCollection() {
this.movies = new ArrayList<Movie>();
}
/**
* Creates a new book collection with the specified list of books pre-defined.
*
* @param books A books list.
*/
public MovieCollection(List<Movie> movies) {
this.movies= movies;
}
public static MovieCollection loadFromJSONFile (File file){
Gson gson = new Gson();
JsonReader jsonReader = null;
try {
jsonReader = new JsonReader(new FileReader(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("Error");
}
return gson.fromJson(jsonReader, MovieCollection.class);
}
预期 BEGIN_OBJECT 但 BEGIN_ARRAY 在第 1 行第 2 列路径 $
该错误清楚地表明您要读取的文本实际上是一个数组,而不是 JSON。它是一个 JSON 的数组。这意味着您需要某种方式来读取对象数组,如下所示:
Gson gson = new Gson();
User[] userArray = gson.fromJson(userJson, User[].class);
这允许您从 json 数组文本中读取用户对象数组。上面代码的示例 json 包含在下面。
[
{
"name": "Alex",
"id": 1
},
{
"name": "Brian",
"id": 2
},
{
"name": "Charles",
"id": 3
}
]
用户 class 定义为
public class User
{
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
此处提供参考 link