如何在Jersey web应用程序中进行自定义JSON Marshaller



我正在使用Jersey运行一个web应用程序。在我的控制器中,我试图在资源中获取一个文件,并返回一个包含enum的对象。enum里面还有两个字段。当对象被编组时,我会收到错误:

jakarta.xml.bind.JAXBException: class java.util.ArrayList nor any of its super class is known to this context.
at org.glassfish.jaxb.runtime.v2.runtime.JAXBContextImpl.getBeanInfo(JAXBContextImpl.java:541)
at org.glassfish.jaxb.runtime.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:445)
at org.glassfish.jaxb.runtime.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:268)
at org.glassfish.jaxb.runtime.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:196)
at jakarta.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:80)
at com.jtv.insights.controller.IngestionController.getIngestionLogDetails(IngestionController.java:194)

我的代码是:

@GET
@Path(value = "/log/details/{fileId}")
@Produces(MediaType.APPLICATION_JSON)
public List<IngestionLogs> getIngestionLogDetails(@PathParam("fileId") String fileId) {
List<IngestionLogs> logs = new ArrayList<>();
// added data in list
try {
JAXBContext ctx = JAXBContext.newInstance(new Class[] { IngestionLogs.class });
Marshaller jsonMarshaller = ctx.createMarshaller();
jsonMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jsonMarshaller.setAdapter(new LogsAdapter());
jsonMarshaller.marshal(logs, response.getOutputStream());
return logs;
} catch (JAXBException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return new ArrayList<>();
}

我的目标是:

@XmlJavaTypeAdapter(LogsAdapter.class)
public class IngestionLogs {
private LogType type;
private String message;
private LocalDateTime lastModified;
private String fileName;
private int rowNumber;
private int columnNumber;
private String cellValue;
private String columnName;
// getters & setters
}

我该如何修复这个错误,创建一个自定义函数来整理我的对象并将此列表作为JSON返回?

您可以省略属性映射,而您的类com.jtv.inights.tool.model.IngitionLogs需要有一个不带参数的默认构造函数(public IngestionLogs(({}(。

最新更新