我有以下json有效负载:
{
"foo" : "bar",
"foo2" : "TCFNhbiBKb3NlMRgwFgYDVQQK"
}
值Json key foo2
的值是一个base64编码的Json字符串。例如,当foo2
的值为Base64.decoded()时,上面的Json看起来像这样:
{
"foo" : "bar",
"foo2" : "{"cat":"meow","dog":"woof"}"
}
当前解决方案
public class Message {
public String foo;
public AnimalSound foo2;
}
public class AnimalSound {
public String cat;
public String dog;
}
public class AnimalSoundAdapter {
private final Moshi moshi;
public AnimalSoundAdapter(Moshi moshi) {
this.moshi = moshi;
}
/** toJson omitted */
@FromJson AnimalSound fromJson(String foo2) {
//base64 decode
String decoded = Base64.decode(foo2);
//deserialize the json string to the pojo
return moshi.adapter(AnimalSound.class).fromJson(decoded);
}
}
客户端代码如下所示:
Moshi moshi = new Moshi.Builder()
.add(new AnimalSoundAdapter(new Moshi.Builder().build()))
.build();
JsonAdapter<Message> adapter = moshi.adapter(Message.class);
Message message = adapter.fromJson(json);
有更好的解决方案吗?
我想知道是否可以避免AnimalSoundAdapter
需要一个Moshi实例。