Base64 decode then deserialize json to pojo with Moshi

匆匆过客 提交于 2019-12-10 23:49:59

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!