Я пытаюсь заполнить JTable POJOS, которую я извлек, используя Gson (). Используя отладчик или печатая значения на консоль с помощью toString (), я вижу, что сопоставление объектов прошло успешно. Моя проблема заключается в заполнении моего пользовательского Jtable объектами.
Проблема: Мой графический интерфейс содержит кнопку, которая берет поле поиска и отправляет его в API, который возвращает ответ в формате JSON, который я правильно отображаю, но не знаю, как получитьданные в таблицу.
Что я пробовал : методы addFilings () и insertFilings () возвращают: Метод addFilings (Filing) в типе FilingsTableModel не являетсяприменимо для аргументов (ExtractorClass)
Коды
Вот класс подачи с методами получения и установки и методом toString ():
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Filing {
@SerializedName("id")
@Expose
private static String id;
@SerializedName("filing_date")
@Expose
private FilingDate filingDate;
@SerializedName("accepted_date")
@Expose
private AcceptedDate acceptedDate;
@SerializedName("period_end_date")
@Expose
private PeriodEndDate periodEndDate;
@SerializedName("report_type")
@Expose
private String reportType;
@SerializedName("sec_unique_id")
@Expose
private String secUniqueId;
@SerializedName("filing_url")
@Expose
private String filingUrl;
@SerializedName("report_url")
@Expose
private String reportUrl;
public String getId() {
return id;
}
public void setId(String id) {
Filing.id = id;
}
public FilingDate getFilingDate() {
return filingDate;
}
public void setFilingDate(FilingDate filingDate) {
this.filingDate = filingDate;
}
public AcceptedDate getAcceptedDate() {
return acceptedDate;
}
public void setAcceptedDate(AcceptedDate acceptedDate) {
this.acceptedDate = acceptedDate;
}
public PeriodEndDate getPeriodEndDate() {
return periodEndDate;
}
public void setPeriodEndDate(PeriodEndDate periodEndDate) {
this.periodEndDate = periodEndDate;
}
public String getReportType() {
return reportType;
}
public void setReportType(String reportType) {
this.reportType = reportType;
}
public String getSecUniqueId() {
return secUniqueId;
}
public void setSecUniqueId(String secUniqueId) {
this.secUniqueId = secUniqueId;
}
public String getFilingUrl() {
return filingUrl;
}
public void setFilingUrl(String filingUrl) {
this.filingUrl = filingUrl;
}
public String getReportUrl() {
return reportUrl;
}
public void setReportUrl(String reportUrl) {
this.reportUrl = reportUrl;
}
public String toString() {
return "[id: " + id + ", Filing Date: " + filingDate.year + "/" + filingDate.month + "/" + filingDate.day
+ ", report_type: " + reportType + ", Report url: " + reportUrl + "]";
}
}
Вот класс Extractor для сопоставления объектов:
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ExtractorClass {
@SerializedName("filings")
@Expose
private List<Filing> filings = null;
@SerializedName("company")
@Expose
private Company company;
@SerializedName("next_page")
@Expose
private String nextPage;
public List<Filing> getFilings() {
return filings;
}
public void setFilings(List<Filing> filings) {
this.filings = filings;
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
public String getNextPage() {
return nextPage;
}
public void setNextPage(String nextPage) {
this.nextPage = nextPage;
}
}
Вот JButton в главном окне приложения:
JButton btnNewButton = new JButton("Search");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
ApiKeyAuth auth = (ApiKeyAuth) defaultClient.getAuthentication("ApiKeyAuth");
auth.setApiKey("API_KEY");
// String identifier = "AAPL"; // String | A Company identifier (Ticker,
// CIK, LEI, Intrinio ID)
String reportType = null; // String | Filter by report type [see -
// /documentation/sec_filing_report_types]. Separate values with commas to
// return multiple report types.
LocalDate startDate = null; // LocalDate | Filed on or after the given date
LocalDate endDate = null; // LocalDate | Filed before or after the given date
Integer pageSize = 50; // Integer | The number of results to return
String nextPage = null; // String | Gets the next page of data from a previous API call
String userInput = null;
CompanyApi companyApi = new CompanyApi();
userInput = textField.getText().trim().toUpperCase();
String identifier = userInput;
try {
ApiResponseCompanyFilings result = companyApi.getCompanyFilings(identifier, reportType, startDate,
endDate, pageSize, nextPage);
String convertedResult = new Gson().toJson(result);
ExtractorClass extractedObjects = new Gson().fromJson(convertedResult, ExtractorClass.class);
model.addFilings(extractedObjects);
} catch (ApiException e) {
System.err.println("Exception when calling CompanyApi#getCompanyFilings");
e.printStackTrace();
}
}
});
И, наконец, пользовательская таблица:
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
import com.g4ther.SECextractor.Date;
import com.g4ther.SECextractor.Filing;
import com.g4ther.SECextractor.FilingDate;
public class FilingsTableModel extends AbstractTableModel
{
private String[] columnNames =
{
"ID",
"Filing Date",
"Report Type",
"Report URL"
};
private List<Filing> filings;
public FilingsTableModel()
{
filings = new ArrayList<Filing>();
}
public FilingsTableModel(List<Filing> filings)
{
this.filings = filings;
}
public int getColumnCount()
{
return columnNames.length;
}
public String getColumnName(int column)
{
return columnNames[column];
}
public int getRowCount()
{
return filings.size();
}
@Override
public Class getColumnClass(int column)
{
switch (column)
{
case 2: return Date.class;
default: return String.class;
}
}
@Override
public boolean isCellEditable(int row, int column)
{
switch (column)
{
case 2: return true; // only the birth date is editable
default: return false;
}
}
@Override
public Object getValueAt(int row, int column)
{
Filing filing = getFiling(row);
switch (column)
{
case 0: return filing.getId();
case 1: return filing.getFilingDate();
case 2: return filing.getReportType();
case 3: return filing.getReportUrl();
default: return null;
}
}
@Override
public void setValueAt(Object value, int row, int column)
{
Filing filing = getFiling(row);
switch (column)
{
case 0: ((Filing) filing).setId((String)value); break;
case 1: ((Filing) filing).setFilingDate((FilingDate)value); break;
case 2: ((Filing) filing).setReportType((String)value); break;
case 3: ((Filing) filing).setReportUrl((String)value); break;
}
fireTableCellUpdated(row, column);
}
public Filing getFiling(int row)
{
return filings.get( row );
}
public void addFilings(Filing filing)
{
insertFilings(getRowCount(), filing);
}
public void insertFilings(int row, Filing filing)
{
filings.add(row, filing);
fireTableRowsInserted(row, row);
}
}
![GUI](https://i.stack.imgur.com/SmE6F.jpg)
Исходный ответ API :
{
"filings": [
{
"id": "fil_95GBZB",
"filing_date": {
"year": 2019,
"month": 10,
"day": 30
},
"accepted_date": {
"dateTime": {
"date": {
"year": 2019,
"month": 10,
"day": 30
},
"time": {
"hour": 16,
"minute": 30,
"second": 40,
"nano": 0
}
},
"offset": {
"totalSeconds": 0
}
},
"period_end_date": {
"year": 2019,
"month": 10,
"day": 30
},
"report_type": "8-K",
"sec_unique_id": "0000320193-19-000117",
"filing_url": "https://www.sec.gov/Archives/edgar/data/320193/000032019319000117/0000320193-19-000117-index.htm",
"report_url": "https://www.sec.gov/ix?doc\u003d/Archives/edgar/data/320193/000032019319000117/a8-kq420199282019.htm",
"instance_url": "https://www.sec.gov/Archives/edgar/data/320193/000032019319000117/aapl-20191030.xsd"
}
],
"company": {
"id": "com_NX6GzO",
"ticker": "AAPL",
"name": "Apple Inc",
"lei": "HWUPKR0MPOU8FGXBT394",
"cik": "0000320193"
},
"next_page": "MjAxOS0xMC0zMHw1NzkxNjc1"
}
После сопоставления и печатиизвлеченные объекты на консоль:
[[id: null, Filing Date: 2019/10/30, report_type: 8-K, Report url: https://www.sec.gov/ix?doc=/Archives/edgar/data/320193/000032019319000117/a8-kq420199282019.htm]]
Действительно застряли здесь, кто-нибудь может мне помочь, пожалуйста?