我正在尝试使用gson库解析json对象数组,因为json语法异常,我无法解析它。我将json文件路径作为参数传递给方法jsonparser。
下面是我解析时遇到问题的示例代码。
test.json - 由对象数组组成
{
"EventRecords": [
{
"eventVersion": "2.0",
"eventSource": "aws:s3",
"awsRegion": "us-east-1",
"eventTime": "2018-05-10T17:10:01.420Z",
"eventName": "ObjectCreated:Put"
}
]
}
GsonParser.java:
public class GsonParser {
public void jsonEncoder(String filePath)
{
Gson gson = new Gson();
Type listType = new TypeToken<List<Record>>(){}.getType();
BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
List<Record> records = gson.fromJson(bufferedReader, listType);
System.out.println("\n\nEventRecords\n\n" + records.toString());
}
public static void main(String[] args) throws IOException {
GsonParser obj= new GsonParser();
File f = new File("/Users/test/Desktop/test.json");
obj.jsonEncoder(f.getAbsolutePath());
}
}
Record.java:
public class Record {
String eventVersion;
String eventSource;
String awsRegion;
String eventTime;
String eventName;
public String getEventVersion() {
return eventVersion;
}
public void setEventVersion(String eventVersion) {
this.eventVersion = eventVersion;
}
public String getEventSource() {
return eventSource;
}
public void setEventSource(String eventSource) {
this.eventSource = eventSource;
}
public String getAwsRegion() {
return awsRegion;
}
public void setAwsRegion(String awsRegion) {
this.awsRegion = awsRegion;
}
public String getEventTime() {
return eventTime;
}
public void setEventTime(String eventTime) {
this.eventTime = eventTime;
}
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
@Override
public String toString () {
return ToStringBuilder.reflectionToString(this,ToStringStyle.MULTI_LINE_STYLE);
}
}
错误:
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
答案 0 :(得分:0)
您的JSON中有对象,而EventRecord是该对象内的数组。
添加课程说 EventRecords
public class EventRecords{
private List<Record> eventRecords = new ArrayList<Record>();
public List<Record> getEventRecords() {
return this.eventRecords;
}
public void setEventRecords(List<Record> records) {
this.eventRecords= records;
}
}
将您的反序列化代码更改为
EventRecords eventRecords = gson.fromJson(bufferedReader, listType);
并获取ArrayList更改
List<Record> records = eventRecords.getEventRecords();