JSON conversion between string and byte [] using GSON

I use hibernate to map objects to a database. The client (iOS application) sends me certain objects in JSON format, which I convert to their true representation using the following utility method

/** * Convert any json string to a relevant object type * @param jsonString the string to convert * @param classType the class to convert it too * @return the Object created */ public static <T> T getObjectFromJSONString(String jsonString, Class<T> classType) { if(stringEmptyOrNull(jsonString) || classType == null){ throw new IllegalArgumentException("Cannot convert null or empty json to object"); } try(Reader reader = new StringReader(jsonString)){ Gson gson = new GsonBuilder().create(); return gson.fromJson(reader, classType); } catch (IOException e) { Logger.error("Unable to close the reader when getting object as string", e); } return null; } 

However, the problem is that in my pogo I save the value as a byte [], as seen below (since this is what is stored in the database - blob)

 @Entity @Table(name = "PersonalCard") public class PersonalCard implements Card{ @Id @GeneratedValue @Column(name = "id") private int id; @OneToOne @JoinColumn(name="userid") private int userid; @Column(name = "homephonenumber") protected String homeContactNumber; @Column(name = "mobilephonenumber") protected String mobileContactNumber; @Column(name = "photo") private byte[] optionalImage; @Column(name = "address") private String address; 

Now, of course, the conversion fails because it cannot convert between byte [] and string.

It is the best approach here to modify the constructor to accept a String instead of an array of bytes, and then do the conversion yourself by setting the value of the byte array, or is there a better approach to this.

The error thrown is as follows:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY, but there was STRING on row 1 of column 96 of the $ .optionalImage path

thanks

Edit In fact, even the approach proposed by me will not work due to the way GSON generates an object.

+6
source share
3 answers

You can use this adapter to serialize and deserialize byte arrays in base64. Here is the content.

  public static final Gson customGson = new GsonBuilder().registerTypeHierarchyAdapter(byte[].class, new ByteArrayToBase64TypeAdapter()).create(); // Using Android base64 libraries. This can be replaced with any base64 library. private static class ByteArrayToBase64TypeAdapter implements JsonSerializer<byte[]>, JsonDeserializer<byte[]> { public byte[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return Base64.decode(json.getAsString(), Base64.NO_WRAP); } public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(Base64.encodeToString(src, Base64.NO_WRAP)); } } 

Credit to the author Ori Peleg .

+13
source

From some blog for future reference the link is not available, at least users can link here.

 import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import java.lang.reflect.Type; import java.util.Date; public class GsonHelper { public static final Gson customGson = new GsonBuilder() .registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { @Override public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return new Date(json.getAsLong()); } }) .registerTypeHierarchyAdapter(byte[].class, new ByteArrayToBase64TypeAdapter()).create(); // Using Android base64 libraries. This can be replaced with any base64 library. private static class ByteArrayToBase64TypeAdapter implements JsonSerializer<byte[]>, JsonDeserializer<byte[]> { public byte[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return Base64.decode(json.getAsString(), Base64.NO_WRAP); } public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(Base64.encodeToString(src, Base64.NO_WRAP)); } } } 
+2
source

You can simply take the photo as a String in POJO, and in the Setter method, convert String to byte [] and return byte [] in the Getter method

 @Entity @Table(name = "PersonalCard") public class PersonalCard implements Card { @Id @GeneratedValue @Column(name = "id") private int id; @OneToOne @JoinColumn(name="userid") private int userid; @Column(name = "homephonenumber") protected String homeContactNumber; @Column(name = "mobilephonenumber") protected String mobileContactNumber; @Column(name = "photo") private byte[] optionalImage; @Column(name = "address") private String address; @Column byte[] optionalImage; public byte[] getOptionalImage() { return optionalImage; } public void setOptionalImage(String s) { this.optionalImage= s.getBytes(); } } 
0
source

Source: https://habr.com/ru/post/974411/


All Articles