How can I serialize/deserialize java.util.stream.Stream using Jackson?

前端 未结 4 1599
星月不相逢
星月不相逢 2021-01-14 14:22

Assuming I have the following object

public class DataObjectA {
    private Stream dataObjectBStream;
}

How can I serial

4条回答
  •  醉话见心
    2021-01-14 15:03

    I had below class having 2 elements one of them was Stream, had to annotate the getterStream method with@JsonSerializer and then override Serialize method, produces stream of JSON in my Response API:

    public class DataSetResultBean extends ResultBean { private static final long serialVersionUID = 1L;

    private final List structure;
    private final Stream datapoints;
    
    private static class DataPointSerializer extends JsonSerializer> 
    {
        @Override
        public void serialize(Stream stream, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException
        {
            gen.writeStartArray();
            try
            {
                stream.forEach(dp -> serializeSingle(gen, dp));
            }
            catch (UncheckedIOException e)
            {
                throw (IOException) e.getCause();
            }
            finally
            {
                stream.close();
            }
            gen.writeEndArray();
        }
        
        public synchronized void serializeSingle(JsonGenerator gen, DataPoint dp) throws UncheckedIOException
        {
            try
            {
                gen.writeStartObject();
                
                for (Entry, ScalarValue> entry: dp.entrySet())
                {
                    gen.writeFieldName(entry.getKey().getName());
                    gen.writeRawValue(entry.getValue().toString());
                }
                
                gen.writeEndObject();
            }
            catch (IOException e)
            {
                throw new UncheckedIOException(e);
            }
        }
    }
    
    public DataSetResultBean(DataSet dataset)
    {
        super("DATASET");
        
        structure = dataset.getMetadata().stream().map(ComponentBean::new).collect(toList());
        datapoints = dataset.stream();
    }
    
    public List getStructure()
    {
        return structure;
    }
    
    @JsonSerialize(using = DataPointSerializer.class)
    public Stream getDatapoints()
    {
        return datapoints;
    }
    

    }

提交回复
热议问题