Esempio n. 1
0
 public static String jsonify(final Object all, final Class<?> view) {
   final ObjectWriter writer = OBJECT_MAPPER.writerWithView(view);
   try {
     return writer.writeValueAsString(all);
   } catch (final JsonGenerationException e) {
     LOG.warn("Error generating JSON", e);
   } catch (final JsonMappingException e) {
     LOG.warn("Error generating JSON", e);
   } catch (final IOException e) {
     LOG.warn("Error generating JSON", e);
   }
   return "";
 }
Esempio n. 2
0
  /**
   * Converts object to JSON string, using a view class for property filtering.
   *
   * @param o object to convert.
   * @param view {@link Class} used for filtering.
   * @return JSON string.
   */
  public static String objectToJsonString(Object o, Class<?> view) {
    ObjectMapper mapper = new ObjectMapper();

    // mapper.configure(SerializationConfig.Feature.DEFAULT_VIEW_INCLUSION,false);
    try {
      if (view != null) {
        return mapper.writerWithView(view).writeValueAsString(o);
      }
      return mapper.writeValueAsString(o);
    } catch (Exception e) {
      log.info(String.format("JsonUtils.objectToJsonString(): Unable to write to string"));
    }
    return null;
  }
  public static String toJson(Object pojo, Class<?> viewClass, boolean prettyPrint)
      throws JsonException {
    try {
      StringWriter sw = new StringWriter();
      JsonGenerator jg = createJsonGenerator(sw);

      if (prettyPrint) {
        jg.useDefaultPrettyPrinter();
      }

      m.writerWithView(viewClass).writeValue(jg, pojo);
      return sw.toString();
    } catch (JsonParseException e) {
      throw new JsonException(e);
    } catch (JsonMappingException e) {
      throw new JsonException(e);
    } catch (IOException e) {
      throw new JsonException(e);
    }
  }
Esempio n. 4
0
 @Override
 public CharSequence apply(final Object context, final Options options) throws IOException {
   if (context == null) {
     return "";
   }
   String viewName = options.hash("view", "");
   final ObjectWriter writer;
   if (viewName.length() > 0) {
     try {
       Class<?> viewClass = alias.get(viewName);
       if (viewClass == null) {
         viewClass = getClass().getClassLoader().loadClass(viewName);
       }
       writer = mapper.writerWithView(viewClass);
     } catch (ClassNotFoundException ex) {
       throw new IllegalArgumentException(viewName, ex);
     }
   } else {
     writer = mapper.writer();
   }
   return new Handlebars.SafeString(writer.writeValueAsString(context));
 }