0

I have been successfully using fromJson function in Android for many different types of objects including String. But for the first time the returned object is a URL string and this seems to pose problem. Here is the code I use:

Gson gson = new Gson();
JSONObject jsonObj = new JSONObject(responseString);
String returnedLink = gson.fromJson(jsonObj.getJSONObject("data").getString("getUrl"), String.class);

If the responseString is in the form

{"data":{"getUrl":"https://domain.com/folder/something"}}

I get a MalformedJsonException.
If I set responseString to

{"data":{"getUrl":"httpsdomain.com.folder.something"}}

returnLink is correctly set to "httpsdomain.com.folder.something"
It looks like if the deserializer was trying to decode the url string and got confused.
Any hint, anyone ?

1
  • try to eescape / characters Commented Jan 20, 2017 at 8:50

1 Answer 1

2

I think there is problem in GSON library. It uses reflection to extract your data, so something can be really messed up.

I recomend you not to use GSON for really basic types, like Strings or Integers. Use it only for your custom classes. And in your case just do

String returnedLink = jsonObj.getJSONObject("data").getString("getUrl");
Sign up to request clarification or add additional context in comments.

5 Comments

Correct. GSON is not necessary there at all, as only string is needed. And anyway, this is primitive field
That does it. Thanks.
@KonstantinPribluda Yes GSON is the right way to do it. I was just using a generic function which I use for all other Classes in my app. But in the case of String (which is not a primitive type, but a class), it is better to do as Ekalips said.
Actually not. YOu use GSON when you have complex data structure and need databinding and object creattion. In your case JSON is already parsed into structure, and you need just one field - data binding library would be overkill here.
OK. Maybe I was not clear: I ALREADY have implemented GSON functions because I am ALSO using more complex classes than String in JSON structures. My point is that in that case it could make sense to treat String like other more complex objects. But because there is a flaw in GSON library, I have to treat String as a special case, and therefore use Ekalips solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.