0

I am not sure what i am missing here. All I am trying to read response and return boolean. Error I am getting is java.lang.RuntimeException: Unable to invoke no-args constructor for interface javax.json.JsonValue. Register an InstanceCreator with Gson for this type may fix this problem.

response = {StringBuffer@5339} "{  "success": true,  "challenge_ts": "2016-07-26T14:52:29Z",  "hostname": "localhost"}"

response.toString = "{  "success": true,  "challenge_ts": "2016-07-26T14:52:29Z",  "hostname": "localhost"}"

Gson gson = new Gson();

JsonObjectjsonObject = gson.fromJson(response.toString(),String.class); //response type is StringBuffer.

return jsonObject.getBoolean("success");

Thanks for the help.

user557657
  • 856
  • 1
  • 12
  • 35
  • If you want to get JsonObject from string, then you need parser. `gson.fromJson(input, POJOtype)` allows you to convert JSON structure from input into your own POJO object. – Pshemo Jul 26 '16 at 01:51
  • You could also use something like `JsonObject jsonObject = gson.fromJson( stringContent, JsonObject.class);` but Parser is more natural approach. For accessing value via key simply use `get(key)`. It will return another `JsonObject` but you can see it as any type which you expect like if you want to get result as boolean you can use `jsonObject.get("success").getAsBoolean()`. – Pshemo Jul 26 '16 at 02:01
  • @Pshemo I tried this `JsonObject jsonObject = gson.fromJson( stringContent, JsonObject.class);` approach also and I was having the same issue. But using this approach did the job `Type type = new TypeToken>() {}.getType(); Map data = GSON.fromJson(response.toString(), type); – user557657 Jul 26 '16 at 13:14
  • I am puzzled now. Wasn't your goal getting `JsonObject`? Also I find it unusual that you get any error with `gson.fromJson( stringContent, JsonObject.class);`. Could you [edit] your question post your simplified JSON string which would allow us to reproduce this problem? – Pshemo Jul 26 '16 at 14:37
  • I would understand if your `stringContent` would hold an array (you would get different error though and mapping to Map wouldn't work now), but it should work fine if your structure is like `{"key":value, "key2":value2}`. – Pshemo Jul 26 '16 at 14:40
  • @Pshemo just edit my question and added the response I get. – user557657 Jul 26 '16 at 15:00
  • Then I can't reproduce your problem. `JsonObject jsonObject = gson.fromJson("{\"success\": true,\"challenge_ts\":\"2016-07-26T14:52:29Z\",\"hostname\":\"localhost\"}", JsonObject.class); System.out.println(jsonObject.get("success"));` is working fine for me. – Pshemo Jul 26 '16 at 15:04

0 Answers0