Exemplo n.º 1
0
 public DateFormat getDateFormat() {
   if (dateFormat == null) {
     dateFormat = new SimpleDateFormat(dateFormatPattern, lexer.getLocale());
     dateFormat.setTimeZone(lexer.getTimeZone());
   }
   return dateFormat;
 }
Exemplo n.º 2
0
  public void parseExtra(Object object, String key) {
    final JSONLexer lexer = this.lexer; // xxx
    lexer.nextTokenWithColon();
    Type type = null;

    if (extraTypeProviders != null) {
      for (ExtraTypeProvider extraProvider : extraTypeProviders) {
        type = extraProvider.getExtraType(object, key);
      }
    }
    Object value =
        type == null //
            ? parse() // skip
            : parseObject(type);

    if (object instanceof ExtraProcessable) {
      ExtraProcessable extraProcessable = ((ExtraProcessable) object);
      extraProcessable.processExtra(key, value);
      return;
    }

    if (extraProcessors != null) {
      for (ExtraProcessor process : extraProcessors) {
        process.processExtra(object, key, value);
      }
    }
  }
Exemplo n.º 3
0
  public static JSONArray parseArray(String text) {
    if (text == null) {
      return null;
    }

    DefaultJSONParser parser = new DefaultJSONParser(text, ParserConfig.getGlobalInstance());

    JSONArray array;

    JSONLexer lexer = parser.getLexer();
    if (lexer.token() == JSONToken.NULL) {
      lexer.nextToken();
      array = null;
    } else if (lexer.token() == JSONToken.EOF) {
      array = null;
    } else {
      array = new JSONArray();
      parser.parseArray(array);

      parser.handleResovleTask(array);
    }

    parser.close();

    return array;
  }
Exemplo n.º 4
0
 public Object parseKey() {
   if (lexer.token() == JSONToken.IDENTIFIER) {
     String value = lexer.stringVal();
     lexer.nextToken(JSONToken.COMMA);
     return value;
   }
   return parse(null);
 }
Exemplo n.º 5
0
 public final void accept(final int token, int nextExpectToken) {
   final JSONLexer lexer = this.lexer;
   if (lexer.token() == token) {
     lexer.nextToken(nextExpectToken);
   } else {
     throwException(token);
   }
 }
Exemplo n.º 6
0
  @SuppressWarnings("unchecked")
  public <T> T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) {
    JSONLexer lexer = parser.getLexer();

    if (lexer.token() == JSONToken.COMMA) {
      lexer.nextToken(JSONToken.LITERAL_STRING);

      if (lexer.token() != JSONToken.LITERAL_STRING) {
        throw new JSONException("syntax error");
      }

      lexer.nextTokenWithColon(JSONToken.LITERAL_INT);

      if (lexer.token() != JSONToken.LITERAL_INT) {
        throw new JSONException("syntax error");
      }

      long time = lexer.longValue();
      lexer.nextToken(JSONToken.RBRACE);
      if (lexer.token() != JSONToken.RBRACE) {
        throw new JSONException("syntax error");
      }
      lexer.nextToken(JSONToken.COMMA);

      return (T) new java.sql.Time(time);
    }

    Object val = parser.parse();

    if (val == null) {
      return null;
    }

    if (val instanceof java.sql.Time) {
      return (T) val;
    } else if (val instanceof Number) {
      return (T) new java.sql.Time(((Number) val).longValue());
    } else if (val instanceof String) {
      String strVal = (String) val;
      if (strVal.length() == 0) {
        return null;
      }

      long longVal;
      JSONScanner dateLexer = new JSONScanner(strVal);
      if (dateLexer.scanISO8601DateIfMatch()) {
        longVal = dateLexer.getCalendar().getTimeInMillis();
      } else {
        longVal = Long.parseLong(strVal);
      }
      return (T) new java.sql.Time(longVal);
    }

    throw new JSONException("parse error");
  }
Exemplo n.º 7
0
 public final void accept(final int token, int nextExpectToken) {
   final JSONLexer lexer = getLexer();
   if (lexer.token() == token) {
     lexer.nextToken(nextExpectToken);
   } else {
     throw new JSONException(
         "syntax error, expect "
             + JSONToken.name(token)
             + ", actual "
             + JSONToken.name(lexer.token()));
   }
 }
Exemplo n.º 8
0
  public void close() {
    final JSONLexer lexer = getLexer();

    try {
      if (isEnabled(Feature.AutoCloseSource)) {
        if (lexer.token() != JSONToken.EOF) {
          throw new JSONException("not close json text, token : " + JSONToken.name(lexer.token()));
        }
      }
    } finally {
      lexer.close();
    }
  }
Exemplo n.º 9
0
  public ParseContext setContext(Object object, Object fieldName) {
    if (lexer.isEnabled(Feature.DisableCircularReferenceDetect)) {
      return null;
    }

    return setContext(this.context, object, fieldName);
  }
Exemplo n.º 10
0
 public void throwException(int token) {
   throw new JSONException(
       "syntax error, expect "
           + JSONToken.name(token)
           + ", actual "
           + JSONToken.name(lexer.token()));
 }
Exemplo n.º 11
0
  public DefaultJSONParser(final Object input, final JSONLexer lexer, final ParserConfig config) {
    this.lexer = lexer;
    this.input = input;
    this.config = config;
    this.symbolTable = config.getSymbolTable();

    lexer.nextToken(JSONToken.LBRACE); // prime the pump
  }
Exemplo n.º 12
0
  public DefaultJSONParser(final Object input, final JSONLexer lexer, final ParserConfig config) {
    this.lexer = lexer;
    this.input = input;
    this.config = config;
    this.symbolTable = config.symbolTable;

    int ch = lexer.getCurrent();
    if (ch == '{') {
      lexer.next();
      ((JSONLexerBase) lexer).token = JSONToken.LBRACE;
    } else if (ch == '[') {
      lexer.next();
      ((JSONLexerBase) lexer).token = JSONToken.LBRACKET;
    } else {
      lexer.nextToken(); // prime the pump
    }
  }
Exemplo n.º 13
0
  @SuppressWarnings("unchecked")
  public <T> T parseObject(Type type) {
    if (lexer.token() == JSONToken.NULL) {
      lexer.nextToken();
      return null;
    }

    ObjectDeserializer derializer = config.getDeserializer(type);

    try {
      return (T) derializer.deserialze(this, type, null);
    } catch (JSONException e) {
      throw e;
    } catch (Throwable e) {
      throw new JSONException(e.getMessage(), e);
    }
  }
Exemplo n.º 14
0
  public void popContext() {
    if (lexer.isEnabled(Feature.DisableCircularReferenceDetect)) {
      return;
    }

    this.context = this.context.parent;
    contextArray[contextArrayIndex - 1] = null;
    contextArrayIndex--;
  }
Exemplo n.º 15
0
  @SuppressWarnings("unchecked")
  public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
    final JSONLexer lexer = parser.getLexer();
    if (lexer.token() == JSONToken.NULL) {
      lexer.nextToken(JSONToken.COMMA);
      return null;
    }

    Map<Object, Object> map = createMap(type);

    ParseContext context = parser.getContext();

    try {
      parser.setContext(context, map, fieldName);
      return (T) deserialze(parser, type, fieldName, map);
    } finally {
      parser.setContext(context);
    }
  }
Exemplo n.º 16
0
  public ParseContext setContext(ParseContext parent, Object object, Object fieldName) {
    if (lexer.isEnabled(Feature.DisableCircularReferenceDetect)) {
      return null;
    }

    this.context = new ParseContext(parent, object, fieldName);
    addContext(this.context);

    return this.context;
  }
Exemplo n.º 17
0
  @SuppressWarnings("unchecked")
  public <T> T parseObject(Type type, Object fieldName) {
    int token = lexer.token();
    if (token == JSONToken.NULL) {
      lexer.nextToken();
      return null;
    }

    if (token == JSONToken.LITERAL_STRING) {
      if (type == byte[].class) {
        byte[] bytes = lexer.bytesValue();
        lexer.nextToken();
        return (T) bytes;
      }

      if (type == char[].class) {
        String strVal = lexer.stringVal();
        lexer.nextToken();
        return (T) strVal.toCharArray();
      }
    }

    ObjectDeserializer derializer = config.getDeserializer(type);

    try {
      return (T) derializer.deserialze(this, type, fieldName);
    } catch (JSONException e) {
      throw e;
    } catch (Throwable e) {
      throw new JSONException(e.getMessage(), e);
    }
  }
Exemplo n.º 18
0
  @Override
  public void parseField(
      DefaultJSONParser parser, Object object, Type objectType, Map<String, Object> fieldValues) {
    Integer value;

    final JSONLexer lexer = parser.getLexer();
    if (lexer.token() == JSONToken.LITERAL_INT) {
      int val = lexer.intValue();
      lexer.nextToken(JSONToken.COMMA);
      if (object == null) {
        fieldValues.put(fieldInfo.getName(), val);
      } else {
        setValue(object, val);
      }
      return;
    } else if (lexer.token() == JSONToken.NULL) {
      value = null;
      lexer.nextToken(JSONToken.COMMA);
    } else {
      Object obj = parser.parse();

      value = TypeUtils.castToInt(obj);
    }

    if (value == null && getFieldClass() == int.class) {
      // skip
      return;
    }

    if (object == null) {
      fieldValues.put(fieldInfo.getName(), value);
    } else {
      setValue(object, value);
    }
  }
Exemplo n.º 19
0
  public static <T> List<T> parseArray(String text, Class<T> clazz) {
    if (text == null) {
      return null;
    }

    List<T> list;

    DefaultJSONParser parser = new DefaultJSONParser(text, ParserConfig.getGlobalInstance());
    JSONLexer lexer = parser.getLexer();
    if (lexer.token() == JSONToken.NULL) {
      lexer.nextToken();
      list = null;
    } else {
      list = new ArrayList<T>();
      parser.parseArray(clazz, list);

      parser.handleResovleTask(list);
    }

    parser.close();

    return list;
  }
Exemplo n.º 20
0
  public void acceptType(String typeName) {
    JSONLexer lexer = this.lexer;

    lexer.nextTokenWithColon();

    if (lexer.token() != JSONToken.LITERAL_STRING) {
      throw new JSONException("type not match error");
    }

    if (typeName.equals(lexer.stringVal())) {
      lexer.nextToken();
      if (lexer.token() == JSONToken.COMMA) {
        lexer.nextToken();
      }
    } else {
      throw new JSONException("type not match error");
    }
  }
Exemplo n.º 21
0
  @SuppressWarnings("unchecked")
  public static <T> T deserialze(DefaultJSONParser parser) {
    final JSONLexer lexer = parser.getLexer();
    if (lexer.token() == JSONToken.LITERAL_INT) {
      long val = lexer.longValue();
      lexer.nextToken(JSONToken.COMMA);
      return (T) new BigDecimal(val);
    }

    if (lexer.token() == JSONToken.LITERAL_FLOAT) {
      BigDecimal val = lexer.decimalValue();
      lexer.nextToken(JSONToken.COMMA);
      return (T) val;
    }

    Object value = parser.parse();

    if (value == null) {
      return null;
    }

    return (T) TypeUtils.castToBigDecimal(value);
  }
Exemplo n.º 22
0
  @SuppressWarnings("unchecked")
  public static <T> T deserialze(DefaultJSONParser parser) {
    final JSONLexer lexer = parser.lexer;
    if (lexer.token() == JSONToken.LITERAL_INT) {
      String val = lexer.numberString();
      lexer.nextToken(JSONToken.COMMA);
      return (T) Float.valueOf(Float.parseFloat(val));
    }

    if (lexer.token() == JSONToken.LITERAL_FLOAT) {
      float val = lexer.floatValue();
      lexer.nextToken(JSONToken.COMMA);
      return (T) Float.valueOf(val);
    }

    Object value = parser.parse();

    if (value == null) {
      return null;
    }

    return (T) TypeUtils.castToFloat(value);
  }
Exemplo n.º 23
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  public final void parseArray(final Collection array, Object fieldName) {
    final JSONLexer lexer = getLexer();

    if (lexer.token() == JSONToken.SET || lexer.token() == JSONToken.TREE_SET) {
      lexer.nextToken();
    }

    if (lexer.token() != JSONToken.LBRACKET) {
      throw new JSONException(
          "syntax error, expect [, actual "
              + JSONToken.name(lexer.token())
              + ", pos "
              + lexer.pos());
    }

    lexer.nextToken(JSONToken.LITERAL_STRING);

    ParseContext context = this.getContext();
    this.setContext(array, fieldName);
    try {
      for (int i = 0; ; ++i) {
        if (isEnabled(Feature.AllowArbitraryCommas)) {
          while (lexer.token() == JSONToken.COMMA) {
            lexer.nextToken();
            continue;
          }
        }

        Object value;
        switch (lexer.token()) {
          case LITERAL_INT:
            value = lexer.integerValue();
            lexer.nextToken(JSONToken.COMMA);
            break;
          case LITERAL_FLOAT:
            if (lexer.isEnabled(Feature.UseBigDecimal)) {
              value = lexer.decimalValue(true);
            } else {
              value = lexer.decimalValue(false);
            }
            lexer.nextToken(JSONToken.COMMA);
            break;
          case LITERAL_STRING:
            String stringLiteral = lexer.stringVal();
            lexer.nextToken(JSONToken.COMMA);

            if (lexer.isEnabled(Feature.AllowISO8601DateFormat)) {
              JSONScanner iso8601Lexer = new JSONScanner(stringLiteral);
              if (iso8601Lexer.scanISO8601DateIfMatch()) {
                value = iso8601Lexer.getCalendar().getTime();
              } else {
                value = stringLiteral;
              }
              iso8601Lexer.close();
            } else {
              value = stringLiteral;
            }

            break;
          case TRUE:
            value = Boolean.TRUE;
            lexer.nextToken(JSONToken.COMMA);
            break;
          case FALSE:
            value = Boolean.FALSE;
            lexer.nextToken(JSONToken.COMMA);
            break;
          case LBRACE:
            JSONObject object = new JSONObject();
            value = parseObject(object, i);
            break;
          case LBRACKET:
            Collection items = new JSONArray();
            parseArray(items, i);
            value = items;
            break;
          case NULL:
            value = null;
            lexer.nextToken(JSONToken.LITERAL_STRING);
            break;
          case RBRACKET:
            lexer.nextToken(JSONToken.COMMA);
            return;
          case EOF:
            throw new JSONException("unclosed jsonArray");
          default:
            value = parse();
            break;
        }

        array.add(value);
        checkListResolve(array);

        if (lexer.token() == JSONToken.COMMA) {
          lexer.nextToken(JSONToken.LITERAL_STRING);
          continue;
        }
      }
    } finally {
      this.setContext(context);
    }
  }
Exemplo n.º 24
0
  public Object parseArrayWithType(Type collectionType) {
    if (lexer.token() == JSONToken.NULL) {
      lexer.nextToken();
      return null;
    }

    Type[] actualTypes = ((ParameterizedType) collectionType).getActualTypeArguments();

    if (actualTypes.length != 1) {
      throw new JSONException("not support type " + collectionType);
    }

    Type actualTypeArgument = actualTypes[0];

    if (actualTypeArgument instanceof Class) {
      List<Object> array = new ArrayList<Object>();
      this.parseArray((Class<?>) actualTypeArgument, array);
      return array;
    }

    if (actualTypeArgument instanceof WildcardType) {
      WildcardType wildcardType = (WildcardType) actualTypeArgument;

      // assert wildcardType.getUpperBounds().length == 1;
      Type upperBoundType = wildcardType.getUpperBounds()[0];

      // assert upperBoundType instanceof Class;
      if (Object.class.equals(upperBoundType)) {
        if (wildcardType.getLowerBounds().length == 0) {
          // Collection<?>
          return parse();
        } else {
          throw new JSONException("not support type : " + collectionType);
        }
      }

      List<Object> array = new ArrayList<Object>();
      this.parseArray((Class<?>) upperBoundType, array);
      return array;

      // throw new JSONException("not support type : " +
      // collectionType);return parse();
    }

    if (actualTypeArgument instanceof TypeVariable) {
      TypeVariable<?> typeVariable = (TypeVariable<?>) actualTypeArgument;
      Type[] bounds = typeVariable.getBounds();

      if (bounds.length != 1) {
        throw new JSONException("not support : " + typeVariable);
      }

      Type boundType = bounds[0];
      if (boundType instanceof Class) {
        List<Object> array = new ArrayList<Object>();
        this.parseArray((Class<?>) boundType, array);
        return array;
      }
    }

    if (actualTypeArgument instanceof ParameterizedType) {
      ParameterizedType parameterizedType = (ParameterizedType) actualTypeArgument;

      List<Object> array = new ArrayList<Object>();
      this.parseArray(parameterizedType, array);
      return array;
    }

    throw new JSONException("TODO : " + collectionType);
  }
Exemplo n.º 25
0
  public void parseObject(Object object) {
    Class<?> clazz = object.getClass();
    Map<String, FieldDeserializer> setters = config.getFieldDeserializers(clazz);

    if (lexer.token() != JSONToken.LBRACE && lexer.token() != JSONToken.COMMA) {
      throw new JSONException("syntax error, expect {, actual " + lexer.tokenName());
    }

    final Object[] args = new Object[1];

    for (; ; ) {
      // lexer.scanSymbol
      String key = lexer.scanSymbol(symbolTable);

      if (key == null) {
        if (lexer.token() == JSONToken.RBRACE) {
          lexer.nextToken(JSONToken.COMMA);
          break;
        }
        if (lexer.token() == JSONToken.COMMA) {
          if (isEnabled(Feature.AllowArbitraryCommas)) {
            continue;
          }
        }
      }

      FieldDeserializer fieldDeser = setters.get(key);
      if (fieldDeser == null) {
        if (!isEnabled(Feature.IgnoreNotMatch)) {
          throw new JSONException(
              "setter not found, class " + clazz.getName() + ", property " + key);
        }

        lexer.nextTokenWithColon();
        parse(); // skip

        if (lexer.token() == JSONToken.RBRACE) {
          lexer.nextToken();
          return;
        }

        continue;
      } else {
        Method method = fieldDeser.getMethod();
        Class<?> fieldClass = method.getParameterTypes()[0];
        Type fieldType = method.getGenericParameterTypes()[0];
        if (fieldClass == int.class) {
          lexer.nextTokenWithColon(JSONToken.LITERAL_INT);
          args[0] = IntegerDeserializer.instance.deserialze(this, fieldType, null);
        } else if (fieldClass == String.class) {
          lexer.nextTokenWithColon(JSONToken.LITERAL_STRING);
          args[0] = StringDeserializer.deserialze(this);
        } else if (fieldClass == long.class) {
          lexer.nextTokenWithColon(JSONToken.LITERAL_INT);
          args[0] = LongDeserializer.instance.deserialze(this, fieldType, null);
        } else {
          ObjectDeserializer fieldValueDeserializer = config.getDeserializer(fieldClass, fieldType);

          lexer.nextTokenWithColon(fieldValueDeserializer.getFastMatchToken());
          args[0] = fieldValueDeserializer.deserialze(this, fieldType, null);
        }

        try {
          method.invoke(object, args);
        } catch (Exception e) {
          throw new JSONException("set proprety error, " + method.getName(), e);
        }
      }

      if (lexer.token() == JSONToken.COMMA) {
        continue;
      }

      if (lexer.token() == JSONToken.RBRACE) {
        lexer.nextToken(JSONToken.COMMA);
        return;
      }
    }
  }
Exemplo n.º 26
0
  public Object[] parseArray(Type[] types) {
    if (lexer.token() == JSONToken.NULL) {
      lexer.nextToken(JSONToken.COMMA);
      return null;
    }

    if (lexer.token() != JSONToken.LBRACKET) {
      throw new JSONException("syntax error : " + lexer.tokenName());
    }

    Object[] list = new Object[types.length];
    if (types.length == 0) {
      lexer.nextToken(JSONToken.RBRACKET);

      if (lexer.token() != JSONToken.RBRACKET) {
        throw new JSONException("syntax error");
      }

      lexer.nextToken(JSONToken.COMMA);
      return new Object[0];
    }

    lexer.nextToken(JSONToken.LITERAL_INT);

    for (int i = 0; i < types.length; ++i) {
      Object value;

      if (lexer.token() == JSONToken.NULL) {
        value = null;
        lexer.nextToken(JSONToken.COMMA);
      } else {
        Type type = types[i];
        if (type == int.class || type == Integer.class) {
          if (lexer.token() == JSONToken.LITERAL_INT) {
            value = Integer.valueOf(lexer.intValue());
            lexer.nextToken(JSONToken.COMMA);
          } else {
            value = this.parse();
            value = TypeUtils.cast(value, type, config);
          }
        } else if (type == String.class) {
          if (lexer.token() == JSONToken.LITERAL_STRING) {
            value = lexer.stringVal();
            lexer.nextToken(JSONToken.COMMA);
          } else {
            value = this.parse();
            value = TypeUtils.cast(value, type, config);
          }
        } else {
          boolean isArray = false;
          Class<?> componentType = null;
          if (i == types.length - 1) {
            if (type instanceof Class) {
              Class<?> clazz = (Class<?>) type;
              isArray = clazz.isArray();
              componentType = clazz.getComponentType();
            }
          }

          // support varArgs
          if (isArray && lexer.token() != JSONToken.LBRACKET) {
            List<Object> varList = new ArrayList<Object>();

            ObjectDeserializer derializer = config.getDeserializer(componentType);
            int fastMatch = derializer.getFastMatchToken();

            if (lexer.token() != JSONToken.RBRACKET) {
              for (; ; ) {
                Object item = derializer.deserialze(this, type, null);
                varList.add(item);

                if (lexer.token() == JSONToken.COMMA) {
                  lexer.nextToken(fastMatch);
                } else if (lexer.token() == JSONToken.RBRACKET) {
                  break;
                } else {
                  throw new JSONException("syntax error :" + JSONToken.name(lexer.token()));
                }
              }
            }

            value = TypeUtils.cast(varList, type, config);
          } else {
            ObjectDeserializer derializer = config.getDeserializer(type);
            value = derializer.deserialze(this, type, null);
          }
        }
      }
      list[i] = value;

      if (lexer.token() == JSONToken.RBRACKET) {
        break;
      }

      if (lexer.token() != JSONToken.COMMA) {
        throw new JSONException("syntax error :" + JSONToken.name(lexer.token()));
      }

      if (i == types.length - 1) {
        lexer.nextToken(JSONToken.RBRACKET);
      } else {
        lexer.nextToken(JSONToken.LITERAL_INT);
      }
    }

    if (lexer.token() != JSONToken.RBRACKET) {
      throw new JSONException("syntax error");
    }

    lexer.nextToken(JSONToken.COMMA);

    return list;
  }
Exemplo n.º 27
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  public void parseArray(Type type, Collection array, Object fieldName) {
    if (lexer.token() == JSONToken.SET || lexer.token() == JSONToken.TREE_SET) {
      lexer.nextToken();
    }

    if (lexer.token() != JSONToken.LBRACKET) {
      throw new JSONException("exepct '[', but " + JSONToken.name(lexer.token()));
    }

    ObjectDeserializer deserializer = null;
    if (int.class == type) {
      deserializer = IntegerDeserializer.instance;
      lexer.nextToken(JSONToken.LITERAL_INT);
    } else if (String.class == type) {
      deserializer = StringDeserializer.instance;
      lexer.nextToken(JSONToken.LITERAL_STRING);
    } else {
      deserializer = config.getDeserializer(type);
      lexer.nextToken(deserializer.getFastMatchToken());
    }

    ParseContext context = this.getContext();
    this.setContext(array, fieldName);
    try {
      for (int i = 0; ; ++i) {
        if (isEnabled(Feature.AllowArbitraryCommas)) {
          while (lexer.token() == JSONToken.COMMA) {
            lexer.nextToken();
            continue;
          }
        }

        if (lexer.token() == JSONToken.RBRACKET) {
          break;
        }

        if (int.class == type) {
          Object val = IntegerDeserializer.instance.deserialze(this, null, null);
          array.add(val);
        } else if (String.class == type) {
          String value;
          if (lexer.token() == JSONToken.LITERAL_STRING) {
            value = lexer.stringVal();
            lexer.nextToken(JSONToken.COMMA);
          } else {
            Object obj = this.parse();
            if (obj == null) {
              value = null;
            } else {
              value = obj.toString();
            }
          }

          array.add(value);
        } else {
          Object val;
          if (lexer.token() == JSONToken.NULL) {
            lexer.nextToken();
            val = null;
          } else {
            val = deserializer.deserialze(this, type, i);
          }
          array.add(val);
          checkListResolve(array);
        }

        if (lexer.token() == JSONToken.COMMA) {
          lexer.nextToken(deserializer.getFastMatchToken());
          continue;
        }
      }
    } finally {
      this.setContext(context);
    }

    lexer.nextToken(JSONToken.COMMA);
  }
Exemplo n.º 28
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  public final Object parseObject(final Map object, Object fieldName) {
    final JSONLexer lexer = this.lexer;

    if (lexer.token() != JSONToken.LBRACE && lexer.token() != JSONToken.COMMA) {
      throw new JSONException("syntax error, expect {, actual " + lexer.tokenName());
    }

    ParseContext context = this.getContext();
    try {
      boolean setContextFlag = false;
      for (; ; ) {
        lexer.skipWhitespace();
        char ch = lexer.getCurrent();
        if (isEnabled(Feature.AllowArbitraryCommas)) {
          while (ch == ',') {
            lexer.next();
            lexer.skipWhitespace();
            ch = lexer.getCurrent();
          }
        }

        boolean isObjectKey = false;
        Object key;
        if (ch == '"') {
          key = lexer.scanSymbol(symbolTable, '"');
          lexer.skipWhitespace();
          ch = lexer.getCurrent();
          if (ch != ':') {
            throw new JSONException("expect ':' at " + lexer.pos() + ", name " + key);
          }
        } else if (ch == '}') {
          lexer.next();
          lexer.resetStringPosition();
          lexer.nextToken();
          return object;
        } else if (ch == '\'') {
          if (!isEnabled(Feature.AllowSingleQuotes)) {
            throw new JSONException("syntax error");
          }

          key = lexer.scanSymbol(symbolTable, '\'');
          lexer.skipWhitespace();
          ch = lexer.getCurrent();
          if (ch != ':') {
            throw new JSONException("expect ':' at " + lexer.pos());
          }
        } else if (ch == EOI) {
          throw new JSONException("syntax error");
        } else if (ch == ',') {
          throw new JSONException("syntax error");
        } else if ((ch >= '0' && ch <= '9') || ch == '-') {
          lexer.resetStringPosition();
          lexer.scanNumber();
          if (lexer.token() == JSONToken.LITERAL_INT) {
            key = lexer.integerValue();
          } else {
            key = lexer.decimalValue(true);
          }
          ch = lexer.getCurrent();
          if (ch != ':') {
            throw new JSONException("expect ':' at " + lexer.pos() + ", name " + key);
          }
        } else if (ch == '{' || ch == '[') {
          lexer.nextToken();
          key = parse();
          isObjectKey = true;
        } else {
          if (!isEnabled(Feature.AllowUnQuotedFieldNames)) {
            throw new JSONException("syntax error");
          }

          key = lexer.scanSymbolUnQuoted(symbolTable);
          lexer.skipWhitespace();
          ch = lexer.getCurrent();
          if (ch != ':') {
            throw new JSONException("expect ':' at " + lexer.pos() + ", actual " + ch);
          }
        }

        if (!isObjectKey) {
          lexer.next();
          lexer.skipWhitespace();
        }

        ch = lexer.getCurrent();

        lexer.resetStringPosition();

        if (key == JSON.DEFAULT_TYPE_KEY) {
          String typeName = lexer.scanSymbol(symbolTable, '"');
          Class<?> clazz = TypeUtils.loadClass(typeName);

          if (clazz == null) {
            object.put(JSON.DEFAULT_TYPE_KEY, typeName);
            continue;
          }

          lexer.nextToken(JSONToken.COMMA);
          if (lexer.token() == JSONToken.RBRACE) {
            lexer.nextToken(JSONToken.COMMA);
            try {
              Object instance = null;
              ObjectDeserializer deserializer = this.config.getDeserializer(clazz);
              if (deserializer instanceof JavaBeanDeserializer) {
                instance = ((JavaBeanDeserializer) deserializer).createInstance(this, clazz);
              }

              if (instance == null) {
                if (clazz == Cloneable.class) {
                  instance = new HashMap();
                } else {
                  instance = clazz.newInstance();
                }
              }

              return instance;
            } catch (Exception e) {
              throw new JSONException("create instance error", e);
            }
          }

          this.setResolveStatus(TypeNameRedirect);

          if (this.context != null && !(fieldName instanceof Integer)) {
            this.popContext();
          }

          ObjectDeserializer deserializer = config.getDeserializer(clazz);
          return deserializer.deserialze(this, clazz, fieldName);
        }

        if (key == "$ref") {
          lexer.nextToken(JSONToken.LITERAL_STRING);
          if (lexer.token() == JSONToken.LITERAL_STRING) {
            String ref = lexer.stringVal();
            lexer.nextToken(JSONToken.RBRACE);

            Object refValue = null;
            if ("@".equals(ref)) {
              if (this.getContext() != null) {
                refValue = this.getContext().getObject();
              }
            } else if ("..".equals(ref)) {
              ParseContext parentContext = context.getParentContext();
              if (parentContext.getObject() != null) {
                refValue = parentContext.getObject();
              } else {
                addResolveTask(new ResolveTask(parentContext, ref));
                setResolveStatus(DefaultJSONParser.NeedToResolve);
              }
            } else if ("$".equals(ref)) {
              ParseContext rootContext = context;
              while (rootContext.getParentContext() != null) {
                rootContext = rootContext.getParentContext();
              }

              if (rootContext.getObject() != null) {
                refValue = rootContext.getObject();
              } else {
                addResolveTask(new ResolveTask(rootContext, ref));
                setResolveStatus(DefaultJSONParser.NeedToResolve);
              }
            } else {
              addResolveTask(new ResolveTask(context, ref));
              setResolveStatus(DefaultJSONParser.NeedToResolve);
            }

            if (lexer.token() != JSONToken.RBRACE) {
              throw new JSONException("syntax error");
            }
            lexer.nextToken(JSONToken.COMMA);

            return refValue;
          } else {
            throw new JSONException("illegal ref, " + JSONToken.name(lexer.token()));
          }
        }

        if (!setContextFlag) {
          setContext(object, fieldName);
          setContextFlag = true;

          // fix Issue #40
          if (this.context != null && !(fieldName instanceof Integer)) {
            this.popContext();
          }
        }

        Object value;
        if (ch == '"') {
          lexer.scanString();
          String strValue = lexer.stringVal();
          value = strValue;

          if (lexer.isEnabled(Feature.AllowISO8601DateFormat)) {
            JSONScanner iso8601Lexer = new JSONScanner(strValue);
            if (iso8601Lexer.scanISO8601DateIfMatch()) {
              value = iso8601Lexer.getCalendar().getTime();
            }
            iso8601Lexer.close();
          }

          if (object.getClass() == JSONObject.class) {
            object.put(key.toString(), value);
          } else {
            object.put(key, value);
          }
        } else if (ch >= '0' && ch <= '9' || ch == '-') {
          lexer.scanNumber();
          if (lexer.token() == JSONToken.LITERAL_INT) {
            value = lexer.integerValue();
          } else {
            value = lexer.numberValue();
          }

          object.put(key, value);
        } else if (ch == '[') { // 减少嵌套,兼容android
          lexer.nextToken();
          JSONArray list = new JSONArray();
          this.parseArray(list, key);
          value = list;
          object.put(key, value);

          if (lexer.token() == JSONToken.RBRACE) {
            lexer.nextToken();
            return object;
          } else if (lexer.token() == JSONToken.COMMA) {
            continue;
          } else {
            throw new JSONException("syntax error");
          }
        } else if (ch == '{') { // 减少嵌套,兼容android
          lexer.nextToken();
          Object obj = this.parseObject(new JSONObject(), key);
          checkMapResolve(object, key.toString());

          if (object.getClass() == JSONObject.class) {
            object.put(key.toString(), obj);
          } else {
            object.put(key, obj);
          }

          setContext(context, obj, key);

          if (lexer.token() == JSONToken.RBRACE) {
            lexer.nextToken();

            setContext(context);
            return object;
          } else if (lexer.token() == JSONToken.COMMA) {
            continue;
          } else {
            throw new JSONException("syntax error, " + lexer.tokenName());
          }
        } else {
          lexer.nextToken();
          value = parse();
          object.put(key, value);

          if (lexer.token() == JSONToken.RBRACE) {
            lexer.nextToken();
            return object;
          } else if (lexer.token() == JSONToken.COMMA) {
            continue;
          } else {
            throw new JSONException("syntax error, position at " + lexer.pos() + ", name " + key);
          }
        }

        lexer.skipWhitespace();
        ch = lexer.getCurrent();
        if (ch == ',') {
          lexer.next();
          continue;
        } else if (ch == '}') {
          lexer.next();
          lexer.resetStringPosition();
          lexer.nextToken();

          this.setContext(object, fieldName);

          return object;
        } else {
          throw new JSONException("syntax error, position at " + lexer.pos() + ", name " + key);
        }
      }
    } finally {
      this.setContext(context);
    }
  }
Exemplo n.º 29
0
  public Object parse(Object fieldName) {
    final JSONLexer lexer = getLexer();
    switch (lexer.token()) {
      case SET:
        lexer.nextToken();
        HashSet<Object> set = new HashSet<Object>();
        parseArray(set, fieldName);
        return set;
      case TREE_SET:
        lexer.nextToken();
        TreeSet<Object> treeSet = new TreeSet<Object>();
        parseArray(treeSet, fieldName);
        return treeSet;
      case LBRACKET:
        JSONArray array = new JSONArray();
        parseArray(array, fieldName);
        return array;
      case LBRACE:
        JSONObject object = new JSONObject();
        return parseObject(object, fieldName);
      case LITERAL_INT:
        Number intValue = lexer.integerValue();
        lexer.nextToken();
        return intValue;
      case LITERAL_FLOAT:
        Object value = lexer.decimalValue(isEnabled(Feature.UseBigDecimal));
        lexer.nextToken();
        return value;
      case LITERAL_STRING:
        String stringLiteral = lexer.stringVal();
        lexer.nextToken(JSONToken.COMMA);

        if (lexer.isEnabled(Feature.AllowISO8601DateFormat)) {
          JSONScanner iso8601Lexer = new JSONScanner(stringLiteral);
          try {
            if (iso8601Lexer.scanISO8601DateIfMatch()) {
              return iso8601Lexer.getCalendar().getTime();
            }
          } finally {
            iso8601Lexer.close();
          }
        }

        return stringLiteral;
      case NULL:
        lexer.nextToken();
        return null;
      case TRUE:
        lexer.nextToken();
        return Boolean.TRUE;
      case FALSE:
        lexer.nextToken();
        return Boolean.FALSE;
      case NEW:
        lexer.nextToken(JSONToken.IDENTIFIER);

        if (lexer.token() != JSONToken.IDENTIFIER) {
          throw new JSONException("syntax error");
        }
        lexer.nextToken(JSONToken.LPAREN);

        accept(JSONToken.LPAREN);
        long time = ((Number) lexer.integerValue()).longValue();
        accept(JSONToken.LITERAL_INT);

        accept(JSONToken.RPAREN);

        return new Date(time);
      case EOF:
        if (lexer.isBlankInput()) {
          return null;
        }
        throw new JSONException("unterminated json string, pos " + lexer.getBufferPosition());
      case ERROR:
      default:
        throw new JSONException("syntax error, pos " + lexer.getBufferPosition());
    }
  }
Exemplo n.º 30
0
  @SuppressWarnings("rawtypes")
  public static Map parseMap(
      DefaultJSONParser parser, Map<String, Object> map, Type valueType, Object fieldName) {
    JSONLexer lexer = parser.getLexer();

    if (lexer.token() != JSONToken.LBRACE) {
      throw new JSONException("syntax error, expect {, actual " + lexer.token());
    }

    ParseContext context = parser.getContext();
    try {
      for (; ; ) {
        lexer.skipWhitespace();
        char ch = lexer.getCurrent();
        if (parser.isEnabled(Feature.AllowArbitraryCommas)) {
          while (ch == ',') {
            lexer.next();
            lexer.skipWhitespace();
            ch = lexer.getCurrent();
          }
        }

        String key;
        if (ch == '"') {
          key = lexer.scanSymbol(parser.getSymbolTable(), '"');
          lexer.skipWhitespace();
          ch = lexer.getCurrent();
          if (ch != ':') {
            throw new JSONException("expect ':' at " + lexer.pos());
          }
        } else if (ch == '}') {
          lexer.next();
          lexer.resetStringPosition();
          lexer.nextToken(JSONToken.COMMA);
          return map;
        } else if (ch == '\'') {
          if (!parser.isEnabled(Feature.AllowSingleQuotes)) {
            throw new JSONException("syntax error");
          }

          key = lexer.scanSymbol(parser.getSymbolTable(), '\'');
          lexer.skipWhitespace();
          ch = lexer.getCurrent();
          if (ch != ':') {
            throw new JSONException("expect ':' at " + lexer.pos());
          }
        } else {
          if (!parser.isEnabled(Feature.AllowUnQuotedFieldNames)) {
            throw new JSONException("syntax error");
          }

          key = lexer.scanSymbolUnQuoted(parser.getSymbolTable());
          lexer.skipWhitespace();
          ch = lexer.getCurrent();
          if (ch != ':') {
            throw new JSONException("expect ':' at " + lexer.pos() + ", actual " + ch);
          }
        }

        lexer.next();
        lexer.skipWhitespace();
        ch = lexer.getCurrent();

        lexer.resetStringPosition();

        if (key == JSON.DEFAULT_TYPE_KEY) {
          String typeName = lexer.scanSymbol(parser.getSymbolTable(), '"');
          Class<?> clazz = TypeUtils.loadClass(typeName);

          if (clazz == map.getClass()) {
            lexer.nextToken(JSONToken.COMMA);
            if (lexer.token() == JSONToken.RBRACE) {
              lexer.nextToken(JSONToken.COMMA);
              return map;
            }
            continue;
          }

          ObjectDeserializer deserializer = parser.getConfig().getDeserializer(clazz);

          lexer.nextToken(JSONToken.COMMA);

          parser.setResolveStatus(DefaultJSONParser.TypeNameRedirect);

          if (context != null && !(fieldName instanceof Integer)) {
            parser.popContext();
          }

          return (Map) deserializer.deserialze(parser, clazz, fieldName);
        }

        Object value;
        lexer.nextToken();

        if (lexer.token() == JSONToken.NULL) {
          value = null;
          lexer.nextToken();
        } else {
          value = parser.parseObject(valueType);
        }

        map.put(key, value);
        parser.checkMapResolve(map, key);

        parser.setContext(context, value, key);

        final int tok = lexer.token();
        if (tok == JSONToken.EOF || tok == JSONToken.RBRACKET) {
          return map;
        }

        if (tok == JSONToken.RBRACE) {
          lexer.nextToken();
          return map;
        }
      }
    } finally {
      parser.setContext(context);
    }
  }