Search code examples
aem

com.google.gson.JsonSyntaxException when parsing simple JSON Inputstream


I am getting com.google.gson.JsonSyntaxException when parsing simple JSON Inputstream

My json is this.

{ "logdata": [{ "millis": "1000", "light": "333" }, { "millis": "2000", "light": "333" } ] }

Java class -

import java.util.List;
public class Datalist {

private List<NavData> logdata;

/**
 * @return the logdata
 */
public List<NavData> getLogdata() {
    return logdata;
}

/**
 * @param logdata the logdata to set
 */
public void setLogdata(List<NavData> logdata) {
    this.logdata = logdata;
}

public class NavData {

private String millis;

private String light;

/**
 * @return the millis
 */
public String getMillis() {
    return millis;
}

/**
 * @param millis the millis to set
 */
public void setMillis(String millis) {
    this.millis = millis;
}

/**
 * @return the light
 */
public String getLight() {
    return light;
}

/**
 * @param light the light to set
 */
public void setLight(String light) {
    this.light = light;
}

}

Json Input Stream Reader Class - Whereas assetData is the inputStream of above json.

   JsonReader reader = new JsonReader(new InputStreamReader(assetData, "UTF-8"));
   Gson gson = new GsonBuilder().create();

   Datalist out = gson.fromJson(reader, Datalist.class);

   System.out.println(".."+out.getLogdata());

Solution

  • The problem is because you can't cast a list of string to a list with these items:

    {
     "millis": "1000",
     "light": "333",
     "temp": "78.32",
     "vcc": "3.54"
    }
    

    If you want to cast to a list of these items, you need to create a class with these items and the property will be:

    @Expose
    private List<NavData> logdata;
    

    Where NavData is a class with these parameters

    import com.google.gson.annotations.Expose;
    public class NavData {
      @Expose
      private String millis;
      @Expose
      private String light;
    
      public String getMillis() {
          return millis;
      }
      public void setMillis(String millis) {
          this.millis = millis;
      }
      public String getLight() {
          return light;
      }
      public void setLight(String light) {
          this.light = light;
      }
    }
    

    To read the inputStream :

    StringBuilder stringBuilder = new StringBuilder();
    CharBuffer charBuffer = CharBuffer.allocate(1024);
    
    while (yourInputStream.read(charBuffer) > 0) {
          charBuffer.flip();
          stringBuilder.append(charBuffer.toString());
          charBuffer.clear();
    }
    

    finally :

    Gson gson = new GsonBuilder().enableComplexMapKeySerialization()
        .excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
    
    Datalist result = gson.fromJson(stringBuilder.toString(), Datalist.class);