title: Converting JSON between string and byte[] with GSON
body: <p>I'm using hibernate to map objects to the database. A client (an iOS app) sends me particular objects in JSON format which I convert to their true representation using the following utility method:</p>
  <pre><code>/**
       * 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 &lt;T&gt; T getObjectFromJSONString(String jsonString, Class&lt;T&gt; classType) {
          
          if(stringEmptyOrNull(jsonString) || classType == null){
              throw new IllegalArgumentException(&quot;Cannot convert null or empty json to object&quot;);
          }
  
          try(Reader reader = new StringReader(jsonString)){
              Gson gson = new GsonBuilder().create();
              return gson.fromJson(reader, classType);
          } catch (IOException e) {
              Logger.error(&quot;Unable to close the reader when getting object as string&quot;, e);
          }
          return null;
      }
  </code></pre>
  <p>The issue however is, that in my pogo I store the value as a byte[] as can be seen below (as this is what is stored in the database - a blob):</p>
  <pre><code>@Entity
  @Table(name = &quot;PersonalCard&quot;)
  public class PersonalCard implements Card{
      
      @Id @GeneratedValue
      @Column(name = &quot;id&quot;)
      private int id;
      
      @OneToOne
      @JoinColumn(name=&quot;userid&quot;)
      private int userid;
      
      @Column(name = &quot;homephonenumber&quot;)
      protected String homeContactNumber;
      
      @Column(name = &quot;mobilephonenumber&quot;)
      protected String mobileContactNumber;
      
      @Column(name = &quot;photo&quot;)
      private byte[] optionalImage;
      
      @Column(name = &quot;address&quot;)
      private String address;
  </code></pre>
  <p>Now of course, the conversion fails because it can't convert between a byte[] and a String.</p>
  <p>Is the best approach here to change the constructor to accept a String instead of a byte array and then do the conversion myself whilst setting the byte array value or is there a better approach to doing this.</p>
  <p>The error thrown is as follows;</p>
  <blockquote>
  <p>com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
  Expected BEGIN_ARRAY but was STRING at line 1 column 96 path
  $.optionalImage</p>
  </blockquote>
  <p>Thanks.</p>
  <p><strong>Edit</strong> In fact even the approach I suggested will not work due to the way in which GSON generates the object.</p>