java - 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
解决方案
推荐阅读
- eloquent - 如何在 Eloquent 中为 A 和( B 或 C )创建查询
- css - 分页:如何使其响应
- java - Kubernetes pod FileLockException:锁定文件已被另一个进程锁定-neo4j 4.2
- xcode - Xcode 12.5 - 如何放大编辑器字体?
- java - 如何使用 Fragment 创建收藏按钮?
- node.js - 如何在 Mac M1 芯片组上安装带有 NVM 的旧版本 Node.js
- python - 如何使用 Outlook API 获取特定 Outlook 电子邮件的电子邮件
- flutter - 不能无条件访问属性“数量”,因为接收者可以为“空”。尝试使访问有条件(使用'?.')
- python - 如何在 numpy 结构化数组中设置多种类型?
- azure - 如何通过 az cli 创建多个存储复制策略