首页 > 解决方案 > How to inject file contents into Gson serialisation?

问题描述

for an Android app I'm working on I'd like to be able to send a REST POST using Volley with a body byte stream which includes a number of photos on the device.

I'm using Gson to serialize a list of objects. in my Volley Request getBody() method e.g. something like:

final Set<MySession> sessions;
....
new Gson().toJson(sessions).getBytes();

where MySession looks a bit like:

public class MySession {
....
  private Set<MyDefect> defects;
....
}
public class MyDefect {
...
  private Set<String> photoPaths;
...
}

What I have works fine up to a point: the REST call is made and the sessions/defects are serialized pretty much exactly as I want. The only thing I'd like to change is that when the sessions/defects are serialized by Gson, that instead of serializing the photo paths, that the byte arrays for the corresponding images are serialized???

so, the JSON sent would be something like:

[{
....
  "defects":
    [ {
          .... 
          "photos": [ [byte-array-for-photo-1], [byte-array-for-photo-2].....],
           ....
       }

i.e. the "photoPath" bit has been replaced by "photos".

I know you can use Gson with custom Serializers so that the byte array of each image @ photoPath is read in and added as a property for serialization BUT I'd rather not have to load in large image byte arrays into memory. What I'd like to do is to somehow be able to 'inject' a byte object stream as part of the serialization?

I also know that you can use JsonWriters and Appenders with toJson: what I'm not sure about is whether it's possible to use these in combination with a custom serializer to do what I'm trying to do? (Or whether there's another approach I haven't realised?)

Any suggestions welcome! Kind regards, Mike Beale

标签: javaandroidserializationgson

解决方案


推荐阅读