How to write an XML MessageBodyWriter provider with jersey

后端 未结 1 1320
再見小時候
再見小時候 2020-12-31 23:28

I am not trying to solve any problem in particular, but rather I am on a learning path to jersey.

I have an entity class marked like this:

@Entity
@T         


        
相关标签:
1条回答
  • 2021-01-01 00:16

    Typically one would use a MessageBodyWriter to convert objects to data formats that Jersey knows nothing about. Here's an example of translating a TableData domain object to CSV:

    @Singleton
    @Produces("text/csv")
    @Provider
    public class FederationCsvWriter implements MessageBodyWriter<TableData> {
    
      @Override
      public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return TableData.class.isAssignableFrom(type);
      }
    
      @Override
      public long getSize(TableData data, Class<?> type, Type genericType, Annotation annotations[], MediaType mediaType) {
        return -1;
      }
    
      @Override
      public void writeTo(TableData data, Class<?> type, Type genericType, Annotation[] annotations,
          MediaType mediaType, MultivaluedMap<String, Object> headers, OutputStream out) throws IOException {
        Writer osWriter = new OutputStreamWriter(out);
        CSVWriter writer = new CSVWriter(osWriter, ',', '"', "\r\n");
        if (data.getResultCount() > 0) {
          //Write the header
          writer.writeNext(data.getResult().get(0).keySet().toArray(new String[data.getResult().get(0).keySet().size()]));
    
          //Write the data
          for (ModelData row: data.getResult()) {
            writer.writeNext(row.values().toArray(new String[row.values().size()]));
          }
        }
        writer.flush();
      }
    
    }
    

    In your example you could either create XML by inspecting the object yourself and feeding the result to the OutputStream or your could use JAXB (which Jersey uses internally) to marshall the objects directly to the OutputStream. For the purposes of your exercise JAXB is probably more interesting.

    0 讨论(0)
提交回复
热议问题