5

My Sample Json Array :

{ 
 "tag":{
    "id": "1112",
    "AP": "77",
    "data":[
       {
         "name": "position",
         "type": "integer",
         "unit": "meter",
         "value": 5
       },
       {
         "type": "RSSI",
         "unit": "dBm",
         "value": -76
       }
     ]
   }
}

And This is My Code :

public void parse(){
    String json = new String(inPacket.getData());
    JsonElement jelement = new JsonParser().parse(json);
    JsonObject  jobject = jelement.getAsJsonObject();
}

And Exception Code :

Exception in thread "Thread-0" 
    com.google.gson.JsonSyntaxException: 
    com.google.gson.stream.MalformedJsonException: 
    Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 154
      at com.google.gson.JsonParser.parse(JsonParser.java:65)
      at com.google.gson.JsonParser.parse(JsonParser.java:45)

I Dont know about JSON array. But Google Gson library is can help me. How Can I Fix this Problem? Would you please help me?

reinhard.lee
  • 503
  • 4
  • 10
  • 24

2 Answers2

7

If the trim() doesn't work, you can use setLenient:

JsonReader reader = new JsonReader(new StringReader(myFooString));
reader.setLenient(true);
JsonParser.parseReader(reader)
Raven
  • 188
  • 1
  • 7
  • 3
    To avoid the 2 'deprecated' warnings on `new JsonParser().parse(reader)`, you can use the static methods: `JsonParser.parseReader(reader)` – Mr-IDE May 29 '21 at 11:04
1

FIX :: Use String.trim() Method. And This Code is working.

public void parse(){
    String json = new String(inPacket.getData());
    JsonElement jelement = new JsonParser().parse(json.trim());
    JsonObject  jobject = jelement.getAsJsonObject();
}
reinhard.lee
  • 503
  • 4
  • 10
  • 24
  • Very useful. This is discussed in more details at https://stackoverflow.com/questions/11484353/gson-throws-malformedjsonexception – Amol Jan 22 '19 at 15:31