Esempio n. 1
0
  /** Add date to buffer */
  private void date(Date date, Method method) {
    JSON json = null;
    if (method != null) json = method.getAnnotation(JSON.class);
    if (this.formatter == null) this.formatter = new SimpleDateFormat(JSONUtil.RFC3339_FORMAT);

    DateFormat formatter =
        (json != null) && (json.format().length() > 0)
            ? new SimpleDateFormat(json.format())
            : this.formatter;
    this.string(formatter.format(date));
  }
Esempio n. 2
0
  /** Instrospect bean and serialize its properties */
  private void bean(Object object) throws JSONException {
    this.add("{");

    BeanInfo info;

    try {
      Class clazz = object.getClass();

      info =
          ((object == this.root) && this.ignoreHierarchy)
              ? Introspector.getBeanInfo(clazz, clazz.getSuperclass())
              : Introspector.getBeanInfo(clazz);

      PropertyDescriptor[] props = info.getPropertyDescriptors();

      boolean hasData = false;
      for (int i = 0; i < props.length; ++i) {
        PropertyDescriptor prop = props[i];
        String name = prop.getName();
        Method accessor = prop.getReadMethod();
        Method baseAccessor = null;
        if (clazz.getName().indexOf("$$EnhancerByCGLIB$$") > -1) {
          try {
            baseAccessor =
                Class.forName(clazz.getName().substring(0, clazz.getName().indexOf("$$")))
                    .getMethod(accessor.getName(), accessor.getParameterTypes());
          } catch (Exception ex) {
            LOG.debug(ex.getMessage(), ex);
          }
        } else baseAccessor = accessor;

        if (baseAccessor != null) {

          JSON json = baseAccessor.getAnnotation(JSON.class);
          if (json != null) {
            if (!json.serialize()) continue;
            else if (json.name().length() > 0) name = json.name();
          }

          // ignore "class" and others
          if (this.shouldExcludeProperty(clazz, prop)) {
            continue;
          }
          String expr = null;
          if (this.buildExpr) {
            expr = this.expandExpr(name);
            if (this.shouldExcludeProperty(expr)) {
              continue;
            }
            expr = this.setExprStack(expr);
          }

          Object value = accessor.invoke(object, new Object[0]);
          boolean propertyPrinted = this.add(name, value, accessor, hasData);
          hasData = hasData || propertyPrinted;
          if (this.buildExpr) {
            this.setExprStack(expr);
          }
        }
      }

      // special-case handling for an Enumeration - include the name() as
      // a property */
      if (object instanceof Enum) {
        Object value = ((Enum) object).name();
        this.add("_name", value, object.getClass().getMethod("name"), hasData);
      }
    } catch (Exception e) {
      throw new JSONException(e);
    }

    this.add("}");
  }