Skip to content

Instantly share code, notes, and snippets.

@piyush-malaviya
Last active May 11, 2017 05:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piyush-malaviya/5e023870346ce2fba9e4845870747622 to your computer and use it in GitHub Desktop.
Save piyush-malaviya/5e023870346ce2fba9e4845870747622 to your computer and use it in GitHub Desktop.
Print formated json in log screen. it is useful we want to show json data in formatted style in log screen.
import android.util.Log;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import java.util.Map;
public class PrintFormattedJson {
private static final String TAG = PrintFormattedJson.class.getSimpleName();
private static int count = 0;
public static void printJson(JsonElement jsonElementRoot) {
count++;
if (jsonElementRoot instanceof JsonArray) {
for (JsonElement jsonElement : jsonElementRoot.getAsJsonArray()) {
printJson(jsonElement);
}
} else if (jsonElementRoot instanceof JsonObject) {
for (Map.Entry<String, JsonElement> entry : jsonElementRoot.getAsJsonObject().entrySet()) {
String key = entry.getKey();
//Log.d(TAG, getSpace() + "Key: " + key);
if (!(entry.getValue() instanceof JsonPrimitive)) {
Log.e(TAG, getSpace() + key);
printJson(entry.getValue());
} else {
Log.d(TAG, getSpace() + key + " : " + entry.getValue().toString());
}
}
} else {
Log.d(TAG, getSpace() + jsonElementRoot.toString());
}
count--;
return;
}
private static String getSpace() {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < count; i++) {
stringBuilder.append(" | ");
}
return stringBuilder.toString();
}
}
/**
#Input Json#
{
"coord": {
"lon": -122.09,
"lat": 37.39
},
"sys": {
"type": 3,
"id": 168940,
"message": 0.0297,
"country": "US",
"sunrise": 1427723751,
"sunset": 1427768967
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "Sky is Clear",
"icon": "01n"
}
],
"base": "stations",
"main": {
"temp": 285.68,
"humidity": 74,
"pressure": 1016.8,
"temp_min": 284.82,
"temp_max": 286.48
},
"wind": {
"speed": 0.96,
"deg": 285.001
},
"clouds": {
"all": 0
},
"dt": 1427700245,
"id": 0,
"name": "Mountain View",
"cod": 200
}
#Output#
| coord
| | lon : -122.09
| | lat : 37.39
| sys
| | type : 3
| | id : 168940
| | message : 0.0297
| | country : "US"
| | sunrise : 1427723751
| | sunset : 1427768967
| weather
| | | id : 800
| | | main : "Clear"
| | | description : "Sky is Clear"
| | | icon : "01n"
| base : "stations"
| main
| | temp : 285.68
| | humidity : 74
| | pressure : 1016.8
| | temp_min : 284.82
| | temp_max : 286.48
| wind
| | speed : 0.96
| | deg : 285.001
| clouds
| | all : 0
| dt : 1427700245
| id : 0
| name : "Mountain View"
| cod : 200
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment