问题
I have the following json payload:
{
"foo" : "bar",
"foo2" : "TCFNhbiBKb3NlMRgwFgYDVQQK"
}
The value Json key foo2
has a value that is a Json string that is base64 encoded. For example, when the value of foo2
is Base64.decoded(), the above Json would look something like this:
{
"foo" : "bar",
"foo2" : "{"cat":"meow","dog":"woof"}"
}
Current Solution
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);
}
}
The client code would look like this:
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);
Is there a better solution?
I'd like to know if it is possible to avoid AnimalSoundAdapter
needing an instance of Moshi.
来源:https://stackoverflow.com/questions/39236936/base64-decode-then-deserialize-json-to-pojo-with-moshi