JaviSanchezG
JaviSanchezG

Reputation: 143

How do I read JSON as String with Gson?

I'm getting a Json from a WebService and I want to print it as a String in my LogCat. I've tried the following:

Gson gson = new Gson();
HttpEntity getResponseEntity = httpResponse.getEntity();
InputStream is = getResponseEntity.getContent();
Reader reader = new InputStreamReader(is);
Type snsType = new TypeToken<SNSRegister>(){}.getType();
snsRegister = gson.fromJson(reader, snsType);
String jsonString = convertStreamToString(is);

snsRegister is an instance of my serializable class, i'm trying to print the JSON in my logcat by converting the InputStream object to String with the convertStreamtoString method:

static String convertStreamToString(java.io.InputStream is) {
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

but my String is always empty and I don't know why. snsRegister is not null, so that isn't the problem.

Upvotes: 1

Views: 523

Answers (2)

durron597
durron597

Reputation: 32323

If this is really important for you to do, Gson can take a String.

I don't recommend reading the Stream twice, though you can do it with mark() and reset(). Since Gson will deserialize a String in addition to Reader, so you can just pass the String into Gson like this:

HttpEntity getResponseEntity = httpResponse.getEntity();
InputStream is = getResponseEntity.getContent();
String jsonString = convertStreamToString(is);
Log.i("MyTAG", jsonString);

Gson gson = new Gson();
Type snsType = new TypeToken<SNSRegister>() {}.getType();
snsRegister = gson.fromJson(jsonString, snsType);
        

I don't recommend doing this in production though, as the conversion to a String is a lot of extra work. But you can use this temporarily for debugging, obviously; the way you're currently doing it is the best way for production.

Another option would be to convert the SNSRegister object back to JSON with gson.toJson(), but that would be even slower.

Upvotes: 2

pelotasplus
pelotasplus

Reputation: 10052

Most probably your stream has been read once by GSON.

If you really, really want to read it twice you need to reset() a stream but first you have to mark() the position you want to reset to.

But all you want is to print your JSON in logcat just add toString() method to your SNSRegister class or even better user Retrofit logging mechanism.

Upvotes: 1

Related Questions