0

Consider the following class:

class MyObject {
    @JsonProperty("name")
    String name = "Hello world";
    @JsonProperty("data")
    byte[] data = new byte[] {10, 20, 30, 40};
}

In the main class I have:

class Main {
    MyObject mo1 = new MyObject(), mo2 = new MyObject();
    List<MyObject> myList = Arrays.asList(mo1, mo2);
    byte[] serialize() {
        return new ObjectMapper().writeValueAsBytes(myList);
    }
    void deserialize(byte[] in) {
        myList = new ObjectMapper().readValue(in, List.class);
    }
}

What happens is that the value of data is saved as base64 (and it's correct) but when deserializing, data is not being converted back to byte[], rather as _StringWithBase64_.getBytes().

Is there any solution without using custom deserializer, like configuring ObjectMapper to decode base64 when loading into byte[]?

pfoof
  • 195
  • 1
  • 13
  • 1
    `myList = new ObjectMapper().readValue(in, new TypeReference>() { });` – Andreas Sep 22 '18 at 05:36
  • @Andreas, where does that answer his specific question? I do not believe this is a duplicate of that, though I may be missing something. I don't see where that question addresses Jackson's handling of byte arrays. – jhyry Sep 22 '18 at 05:39
  • @Andreas works as charm :) – pfoof Sep 22 '18 at 05:57
  • Fascinating. That is really cool. How does that work? – jhyry Sep 22 '18 at 06:15
  • @jhyry When you call `readValue(in, List.class)`, using a *raw* `List`, it doesn't know what type of object is in the list, i.e. what class to instantiate, so it simply creates a `Map`, i.e. you end up with a `List>`. Creating an anonymous subclass of `TypeReference` allow you to specify the type of object in the `List`. – Andreas Sep 22 '18 at 08:01

0 Answers0