2

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.

MDrabic
  • 917
  • 8
  • 15
  • I wonder why you're using base64 for the field? – Eugen Martynov Aug 31 '16 at 19:23
  • 1
    @EugenMartynov base64'ing the field is not my choice. I'm implementing the [FIDO UAF Protocol Spec](https://fidoalliance.org/specs/fido-uaf-v1.0-ps-20141208/fido-uaf-protocol-v1.0-ps-20141208.html) which requires certain fields be created like this. – MDrabic Aug 31 '16 at 21:28

0 Answers0