Java Code Examples for com.alibaba.fastjson.parser.DefaultJSONParser#parseObject()

The following examples show how to use com.alibaba.fastjson.parser.DefaultJSONParser#parseObject() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PageDeserializer.java    From phone with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked"})
    public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {

    	if (parser.getLexer().token() == JSONToken.NULL) {
            parser.getLexer().nextToken(JSONToken.COMMA);
            return null;
        }
        String input = parser.getInput();
//        final String inputValue = input.replaceAll("\\{.+list:\\[(.++)\\]\\}", "$1");
//        ReflectionUtil.setField(ReflectionUtil.findField(parser.getClass(), "input"), parser,inputValue );
        Page<T> list = null;
        if (null==parser.getInput()||"null".equals(input)) {
			return null;
		}
        JSONObject jo = parser.parseObject();
        JSONArray ja = jo.getJSONArray("list");
        if (ja!=null) {
            List<T> vList = (List<T>) ja;
			list = new Page<>();
			list.addAll(vList);
	        list.setTotal(jo.getIntValue("total"));
		}

        return (T) list;
    }
 
Example 2
Source File: JSON.java    From uavstack with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T parseObject(char[] input, int length, Type clazz, Feature... features) {
    if (input == null || input.length == 0) {
        return null;
    }

    int featureValues = DEFAULT_PARSER_FEATURE;
    for (Feature feature : features) {
        featureValues = Feature.config(featureValues, feature, true);
    }

    DefaultJSONParser parser = new DefaultJSONParser(input, length, ParserConfig.getGlobalInstance(), featureValues);
    T value = (T) parser.parseObject(clazz);

    parser.handleResovleTask(value);

    parser.close();

    return (T) value;
}
 
Example 3
Source File: JSON.java    From uavstack with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T parseObject(String input, Type clazz, int featureValues, Feature... features) {
    if (input == null) {
        return null;
    }

    for (Feature feature : features) {
        featureValues = Feature.config(featureValues, feature, true);
    }

    DefaultJSONParser parser = new DefaultJSONParser(input, ParserConfig.getGlobalInstance(), featureValues);
    T value = (T) parser.parseObject(clazz);

    parser.handleResovleTask(value);

    parser.close();

    return (T) value;
}
 
Example 4
Source File: ReferenceCodec.java    From uavstack with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
    ParameterizedType paramType = (ParameterizedType) type;
    Type itemType = paramType.getActualTypeArguments()[0];

    Object itemObject = parser.parseObject(itemType);

    Type rawType = paramType.getRawType();
    if (rawType == AtomicReference.class) {
        return (T) new AtomicReference(itemObject);
    }

    if (rawType == WeakReference.class) {
        return (T) new WeakReference(itemObject);
    }

    if (rawType == SoftReference.class) {
        return (T) new SoftReference(itemObject);
    }

    throw new UnsupportedOperationException(rawType.toString());
}
 
Example 5
Source File: ReflectUtil.java    From game-server with MIT License 6 votes vote down vote up
/**
 * wzy扩展
 *
 * @param input
 * @param value
 * @param config
 * @param processor
 * @param featureValues
 * @param features
 */
private static void reflectObject(String input, Object value, ParserConfig config, ParseProcess processor,
		int featureValues, Feature... features) {
	if (input == null) {
		return;
	}
	for (Feature featrue : features) {
		featureValues = Feature.config(featureValues, featrue, true);
	}

	DefaultJSONParser parser = new DefaultJSONParser(input, config, featureValues);

	if (processor instanceof ExtraTypeProvider) {
		parser.getExtraTypeProviders().add((ExtraTypeProvider) processor);
	}

	if (processor instanceof ExtraProcessor) {
		parser.getExtraProcessors().add((ExtraProcessor) processor);
	}
	parser.parseObject(value);
	parser.handleResovleTask(value);
	parser.close();
}
 
Example 6
Source File: TestFastJson.java    From util4j with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	TestFastJson entity=new TestFastJson();
	JSONObject json=new JSONObject();
	JSONArray list=new JSONArray();
	list.add(1);
	json.put("1", 1);
	json.put("list",list);
	entity.setJson(json);
	String jsonStr=JSON.toJSONString(entity);
	System.out.println(jsonStr);
	entity=JSONObject.parseObject(jsonStr,TestFastJson.class);
	System.out.println(entity);
	//反序列化
	DefaultJSONParser jp=new DefaultJSONParser(jsonStr);
	JSONObject json2=jp.parseObject();
	System.out.println("id:"+json2.getIntValue("id"));
	//类型反序列化
	Type type=new TypeReference<TestFastJson>() {
	}.getType();
	TestFastJson entity2=JSON.parseObject(jsonStr, type);
	System.out.println(entity2.getId());
}
 
Example 7
Source File: JavaObjectDeserializer.java    From uavstack with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
    if (type instanceof GenericArrayType) {
        Type componentType = ((GenericArrayType) type).getGenericComponentType();
        if (componentType instanceof TypeVariable) {
            TypeVariable<?> componentVar = (TypeVariable<?>) componentType;
            componentType = componentVar.getBounds()[0];
        }

        List<Object> list = new ArrayList<Object>();
        parser.parseArray(componentType, list);
        Class<?> componentClass;
        if (componentType instanceof Class) {
            componentClass = (Class<?>) componentType;
            Object[] array = (Object[]) Array.newInstance(componentClass, list.size());
            list.toArray(array);
            return (T) array;
        } else {
            return (T) list.toArray();
        }

    }
    
    if (type instanceof Class
            && type != Object.class
            && type != Serializable.class
            && type != Cloneable.class
            && type != Closeable.class
            && type != Comparable.class) {
        return (T) parser.parseObject(type);    
    }

    return (T) parser.parse(fieldName);
}
 
Example 8
Source File: FastjsonHttpMessageConverter.java    From java-platform with Apache License 2.0 5 votes vote down vote up
@Override
public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {
	String json = IOUtils.toString(inputMessage.getBody(), getCharset(inputMessage.getHeaders()));
	DefaultJSONParser parser = new DefaultJSONParser(json, this.parserConfig);
	Object value = parser.parseObject(type);

	parser.handleResovleTask(value);

	parser.close();

	return value;
}
 
Example 9
Source File: JSON.java    From uavstack with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T parseObject(String input, Type clazz, ParserConfig config, ParseProcess processor,
                                      int featureValues, Feature... features) {
    if (input == null) {
        return null;
    }

    if (features != null) {
        for (Feature feature : features) {
            featureValues |= feature.mask;
        }
    }

    DefaultJSONParser parser = new DefaultJSONParser(input, config, featureValues);

    if (processor != null) {
        if (processor instanceof ExtraTypeProvider) {
            parser.getExtraTypeProviders().add((ExtraTypeProvider) processor);
        }

        if (processor instanceof ExtraProcessor) {
            parser.getExtraProcessors().add((ExtraProcessor) processor);
        }

        if (processor instanceof FieldTypeResolver) {
            parser.setFieldTypeResolver((FieldTypeResolver) processor);
        }
    }

    T value = (T) parser.parseObject(clazz, null);

    parser.handleResovleTask(value);

    parser.close();

    return (T) value;
}
 
Example 10
Source File: LongCodec.java    From uavstack with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) {
    final JSONLexer lexer = parser.lexer;

    Long longObject;
    try {
        final int token = lexer.token();
        if (token == JSONToken.LITERAL_INT) {
            long longValue = lexer.longValue();
            lexer.nextToken(JSONToken.COMMA);
            longObject = Long.valueOf(longValue);
        } else if (token == JSONToken.LITERAL_FLOAT) {
            BigDecimal number = lexer.decimalValue();
            longObject = TypeUtils.longValue(number);
            lexer.nextToken(JSONToken.COMMA);
        } else {
            if (token == JSONToken.LBRACE) {
                JSONObject jsonObject = new JSONObject(true);
                parser.parseObject(jsonObject);
                longObject = TypeUtils.castToLong(jsonObject);
            } else {
                Object value = parser.parse();

                longObject = TypeUtils.castToLong(value);
            }
            if (longObject == null) {
                return null;
            }
        }
    } catch (Exception ex) {
        throw new JSONException("parseLong error, field : " + fieldName, ex);
    }
    
    return clazz == AtomicLong.class //
        ? (T) new AtomicLong(longObject.longValue()) //
        : (T) longObject;
}
 
Example 11
Source File: AbstractSerializer.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
/**
 * 读取字符串数组
 *
 * @param parser 解析器
 * @param lexer  文法
 * @param field  字段
 */
protected String[] parseStrings(final DefaultJSONParser parser, final JSONLexer lexer, final String field) {
    String result[] = null;
    switch (lexer.token()) {
        case JSONToken.LBRACKET:
            result = parser.parseObject(String[].class);
            break;
        case JSONToken.NULL:
            lexer.nextToken();
            break;
        default:
            throw new SerializerException("syntax error: invalid " + field);
    }
    return result;
}
 
Example 12
Source File: AbstractSerializer.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
/**
 * 读取MAP
 *
 * @param parser 解析器
 * @param lexer  文法
 * @param field  字段
 */
protected Map<String, Object> parseMap(final DefaultJSONParser parser, final JSONLexer lexer, final String field) {
    Map<String, Object> result = null;
    switch (lexer.token()) {
        case JSONToken.LBRACE:
            result = parser.parseObject();
            break;
        case JSONToken.NULL:
            lexer.nextToken();
            break;
        default:
            throw new SerializerException("syntax error: invalid " + field);
    }
    return result;
}
 
Example 13
Source File: IntegerCodec.java    From uavstack with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) {
    final JSONLexer lexer = parser.lexer;

    final int token = lexer.token();

    if (token == JSONToken.NULL) {
        lexer.nextToken(JSONToken.COMMA);
        return null;
    }


    Integer intObj;
    try {
        if (token == JSONToken.LITERAL_INT) {
            int val = lexer.intValue();
            lexer.nextToken(JSONToken.COMMA);
            intObj = Integer.valueOf(val);
        } else if (token == JSONToken.LITERAL_FLOAT) {
            BigDecimal number = lexer.decimalValue();
            intObj = TypeUtils.intValue(number);
            lexer.nextToken(JSONToken.COMMA);
        } else {
            if (token == JSONToken.LBRACE) {
                JSONObject jsonObject = new JSONObject(true);
                parser.parseObject(jsonObject);
                intObj = TypeUtils.castToInt(jsonObject);
            } else {
                Object value = parser.parse();
                intObj = TypeUtils.castToInt(value);
            }
        }
    } catch (Exception ex) {
        throw new JSONException("parseInt error, field : " + fieldName, ex);
    }

    
    if (clazz == AtomicInteger.class) {
        return (T) new AtomicInteger(intObj.intValue());
    }
    
    return (T) intObj;
}
 
Example 14
Source File: YearMonthSerialization.java    From joyrpc with Apache License 2.0 4 votes vote down vote up
@Override
public <T> T deserialze(final DefaultJSONParser parser, final Type type, final Object fieldName) {
    String text = parser.parseObject(String.class);
    return (T) YearMonth.parse(text);
}
 
Example 15
Source File: BaseOperationAdapter.java    From java-unified-sdk with Apache License 2.0 4 votes vote down vote up
public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
  JSONObject jsonObject = parser.parseObject();
  return parseJSONObject(jsonObject);
}
 
Example 16
Source File: ObjectTypeAdapter.java    From java-unified-sdk with Apache License 2.0 4 votes vote down vote up
/**
 * deserializer
 * @param parser json parser
 * @param type type
 * @param fieldName field name
 * @return object.
 *
 * @since 1.8+
 */
public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
  if (!AVObject.class.isAssignableFrom((Class) type)) {
    return (T) parser.parseObject();
  }

  String className = "";
  Map<String, Object> serverJson = null;
  Map<String, Object> objectMap = parser.parseObject(Map.class);
  if (objectMap.containsKey(KEY_VERSION)) {
    // 5.x version
    className = (String) objectMap.get(AVObject.KEY_CLASSNAME);
    if (objectMap.containsKey(KEY_SERVERDATA)) {
      serverJson = (Map<String, Object>) objectMap.get(KEY_SERVERDATA);
    } else {
      serverJson = objectMap;
    }
  } else if (objectMap.containsKey(AVObject.KEY_CLASSNAME)) {
    // android sdk output
    // { "@type":"com.example.avoscloud_demo.Student","objectId":"5bff468944d904005f856849","updatedAt":"2018-12-08T09:53:05.008Z","createdAt":"2018-11-29T01:53:13.327Z","className":"Student","serverData":{"@type":"java.util.concurrent.ConcurrentHashMap","name":"Automatic Tester's Dad","course":["Math","Art"],"age":20}}
    className = (String) objectMap.get(AVObject.KEY_CLASSNAME);
    objectMap.remove(AVObject.KEY_CLASSNAME);
    if (objectMap.containsKey(KEY_SERVERDATA)) {
      ConcurrentHashMap<String, Object> serverData = (ConcurrentHashMap<String, Object>) objectMap.get(KEY_SERVERDATA);//
      objectMap.remove(KEY_SERVERDATA);
      objectMap.putAll(serverData);
    }
    objectMap.remove("operationQueue");
    serverJson = objectMap;
  } else {
    // leancloud server response.
    serverJson = objectMap;
  }
  AVObject obj;
  if (type.toString().endsWith(AVFile.class.getCanonicalName())) {
    obj = new AVFile();
  } else if (type.toString().endsWith(AVUser.class.getCanonicalName())) {
    obj = new AVUser();
  } else if (type.toString().endsWith(AVInstallation.class.getCanonicalName())) {
    obj = new AVInstallation();
  } else if (type.toString().endsWith(AVStatus.class.getCanonicalName())) {
    obj = new AVStatus();
  } else if (type.toString().endsWith(AVRole.class.getCanonicalName())) {
    obj = new AVRole();
  } else if (!StringUtil.isEmpty(className)) {
    obj = Transformer.objectFromClassName(className);
  } else {
    obj = new AVObject();
  }
  for (Map.Entry<String, Object> entry: serverJson.entrySet()) {
    String k = entry.getKey();
    Object v = entry.getValue();
    if (v instanceof String || v instanceof Number || v instanceof Boolean || v instanceof Byte || v instanceof Character) {
      // primitive type
      obj.serverData.put(k, v);
    } else if (v instanceof Map || v instanceof JSONObject) {
      obj.serverData.put(k, Utils.getObjectFrom(v));
    } else if (v instanceof Collection) {
      obj.serverData.put(k, Utils.getObjectFrom(v));
    } else if (null != v) {
      obj.serverData.put(k, v);
    }
  }
  return (T) obj;

}
 
Example 17
Source File: MonthDaySerialization.java    From joyrpc with Apache License 2.0 4 votes vote down vote up
@Override
public <T> T deserialze(final DefaultJSONParser parser, final Type type, final Object fieldName) {
    String text = parser.parseObject(String.class);
    return (T) MonthDay.parse(text);
}
 
Example 18
Source File: AbstractSerializer.java    From joyrpc with Apache License 2.0 2 votes vote down vote up
/**
 * 解析对象
 *
 * @param parser 解析器
 * @param lexer  语法
 * @param type   类型
 * @return
 */
protected Object parseObject(final DefaultJSONParser parser, final JSONLexer lexer, final Type type) {
    return lexer.token() != JSONToken.NULL ? parser.parseObject(type) : null;
}