Я вызываю службу REST третьей стороны для деталей поиска работы и отправляет ответ обратно в формате JSON. Данные JSON выглядитАнализ Java GSON - массив и вложенный класс
[
{
"Id": 1
"County": "sample string 16",
"Country": "sample string 17",
"AtAddressSinceMonth": 1,
"AtAddressSinceYear": 1,
"AtAddressUntilMonth": 1,
"AtAddressUntilYear": 1,
"DateOfBirth": "2013-12-11T14:25:27.3753327-05:00",
"Documents": [
{
"Type": "sample string 1",
"Description": "sample string 2",
"File": "sample string 3"
},
{
"Type": "sample string 1",
"Description": "sample string 2",
"File": "sample string 3"
},
],
"Events": [
{
"StartDateTime": "2013-12-11T14:25:27.3753327-05:00",
"EndDateTime": "2013-12-11T14:25:27.3753327-05:00",
"Description": "sample string 3",
"Attendees": [
{
"EmailAddress": "sample string 1",
"FirstName": "sample string 2",
"LastName": "sample string 3"
},
{
"EmailAddress": "sample string 1",
"FirstName": "sample string 2",
"LastName": "sample string 3"
}
]
},
{
"StartDateTime": "2013-12-11T14:25:27.3753327-05:00",
"EndDateTime": "2013-12-11T14:25:27.3753327-05:00",
"Description": "sample string 3",
"Attendees": [
{
"EmailAddress": "sample string 1",
"FirstName": "sample string 2",
"LastName": "sample string 3"
},
....
....
{
"Id": 1,
"County": "sample string 16",
"Country": "sample string 17",
"AtAddressSinceMonth": 1,
"AtAddressSinceYear": 1,
"AtAddressUntilMonth": 1,
"AtAddressUntilYear": 1,
...
...
}
]
}
]
и это продолжается, как that..I've defincd статического класса JobSeeker со всеми переменными и статическим внутренним классом для всех вложенных variables..with соответствующего набора и получить методы. .
Кроме того, создал еще один класс ArrayOfJobSeeker с переменной защищаемого Список JobSeeker, Мое определение класса выглядит как
public class ArrayOfJobSeeker {
protected List<ArrayOfJobSeeker.JobSeeker> jobSeeker;
public List<ArrayOfJobSeeker.JobSeeker> getJobSeeker() {
if (jobSeeker == null) {
jobSeeker = new ArrayList<ArrayOfJobSeeker.JobSeeker>();
}
return this.jobSeeker;
}
public static class JobSeeker {
protected String address;
protected String atAddressSinceMonth;
protected String atAddressSinceYear;
protected String atAddressUntilMonth;
protected String atAddressUntilYear;
protected String city;
protected String country;
protected String county;
protected XMLGregorianCalendar dateOfBirth;
protected ArrayOfJobSeeker.JobSeeker.Documents documents;
protected String emailAddress;
protected ArrayOfJobSeeker.JobSeeker.Events events;
protected String extension;
protected String firstName;
protected String genderCode;
protected ArrayOfJobSeeker.JobSeeker.HistoryActivities historyActivities;
protected String id;
protected String lastName;
protected String maidenName;
protected String middleName;
и вложенные внутренние классы
public static class Documents {
protected List<ArrayOfJobSeeker.JobSeeker.Documents.Document> document;
public List<ArrayOfJobSeeker.JobSeeker.Documents.Document> getDocument() {
if (document == null) {
document = new ArrayList<ArrayOfJobSeeker.JobSeeker.Documents.Document>();
}
return this.document;
}
public static class Document {
protected String description;
protected String file;
protected String type;
} //end Document
} // end Documents
} // конец ищущий работу
Я совсем не уверен, как разобрать этот вложенный массив с GSON, как этот код генерирует ошибку
File file = new File("c:/temp/testJSON.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
Gson gson = new Gson();
gson.fromJson(br, ArrayOfJobSeeker.class)
Пожалуйста, помогите.
Благодаря
Какая ошибка? Один из методов, который я нашел эффективным в таких случаях, заключается в создании структуры данных в памяти и приведении ее в строку (в этом случае с использованием 'toJson()'), сохранение в файл и сравнение с текстом, который вы пытаетесь проанализировать –
Внутренние классы 'static' не отличаются от классов верхнего уровня, когда речь заходит о сериализации и десериализации. –
У меня возникли проблемы с созданием собственных классов Java на основе JSON, но я нашел это [json gen tool] (http://jsongen.byingtondesign.com/) действительно полезным –