Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.devbliss.doctest.utils;
  
  import java.util.List;
  
Utils class used to transform object into json-formatted java.lang.String

Author(s):
bmary
mbankmann
 
 public class JSONHelper {

    
Converts the given POJO into a Json representation.

Parameters:
obj
Returns:
 
     public String toJson(Object obj) {
         return toJson(objfalse);
     }

    
Converts the given POJO into a Json representation. If prettyPrint is true, the output will be nicely formatted.

Parameters:
obj
prettyPrint
Returns:
 
     public String toJson(Object objboolean prettyPrint) {
         GsonBuilder builder = new GsonBuilder();
 
         if (prettyPrint) {
             builder.setPrettyPrinting();
         }
 
         return builder.create().toJson(obj);
     }

    
Converts the given POJO to Json and will skip the given fields while doing so.

Parameters:
obj
excludedFields
Returns:
 
     public String toJsonAndSkipCertainFields(Object objfinal List<StringexcludedFields) {
         return toJsonAndSkipCertainFields(objexcludedFieldsfalse);
     }

    
Converts the given POJO and will skip the given fields while doing so. If prettyPrint is true, the output will be nicely formatted.

Parameters:
obj
excludedFields
prettyPrint
Returns:
 
     public String toJsonAndSkipCertainFields(Object objfinal List<StringexcludedFields,
             boolean prettyPrint) {
         ExclusionStrategy strategy = new ExclusionStrategy() {
             public boolean shouldSkipField(FieldAttributes f) {
                 if (excludedFields.contains(f.getName())) {
                     return true;
                 }
 
                 return false;
             }
 
             public boolean shouldSkipClass(Class<?> clazz) {
                 return false;
             }
         };
 
         GsonBuilder builder =
                 new GsonBuilder().addSerializationExclusionStrategy(strategy)
                         .addDeserializationExclusionStrategy(strategy);
 
         if (prettyPrint)
             builder.setPrettyPrinting();
 
         return builder.create().toJson(obj);
     }
 
     public boolean isJsonValid(String json) {
         return json != null && !json.equals("null") && !json.isEmpty() && json.startsWith("{");
    }

    
Pretty prints any json input.

Parameters:
json
Returns:
    public String prettyPrintJson(String json) {
        if (!isJsonValid(json)) {
            return json;
        }
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        JsonParser jp = new JsonParser();
        JsonElement je = jp.parse(json);
        String returnvalue = gson.toJson(je);
        return returnvalue;
    }
New to GrepCode? Check out our FAQ X