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
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.
source share