Search code examples
androidstringgsoninputstreamlogcat

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.


Solution

  • 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.