com.alibaba.fastjson.serializer.JSONSerializer Java Examples

The following examples show how to use com.alibaba.fastjson.serializer.JSONSerializer. 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: BackupShardSerializer.java    From joyrpc with Apache License 2.0 6 votes vote down vote up
@Override
public void write(final JSONSerializer serializer, final Object object, final Object fieldName, final Type fieldType, final int features) throws IOException {
    if (object == null) {
        serializer.writeNull();
    } else {
        SerializeWriter out = serializer.getWriter();
        out.write('{');
        BackupShard backupShard = (BackupShard) object;
        writeString(out, "name", backupShard.getName());
        writeString(out, "region", backupShard.getRegion());
        writeString(out, "dataCenter", backupShard.getDataCenter());
        writeString(out, "protocol", backupShard.getProtocol());
        writeString(out, "address", backupShard.getAddress());
        out.writeFieldName("weight");
        out.writeInt(backupShard.getWeight());
        out.write('}');
    }
}
 
Example #2
Source File: JsonUtil.java    From game-server with MIT License 6 votes vote down vote up
/**
 * 对象转json
 * <p>
 * 需要jsonFiled注解
 * </p>
 *
 * @param object a {@link java.lang.Object} object.
 * @return a {@link java.lang.String} object.
 */
public static String toJSONString(Object object) {
	SerializeWriter out = new SerializeWriter();
	try {
		Map<String, Field> fieldCacheMap = new HashMap<>();
		ParserConfig.parserAllFieldToCache(object.getClass(), fieldCacheMap);
		JSONSerializer serializer = new JSONSerializer(out);
		PropertyFilter filter = (Object source, String name, Object value) -> {
			Field field = ParserConfig.getFieldFromCache(name, fieldCacheMap);
			if (field != null) {
				JSONField fieldAnnotation = field.getAnnotation(JSONField.class);
				if (fieldAnnotation != null) {
					return true;
				}
				return false;
			}
			return true;
		};
		serializer.getPropertyFilters().add(filter);
		serializer.write(object);
		return out.toString();
	} finally {
		out.close();
	}
}
 
Example #3
Source File: ComplexPropertyPreFilter.java    From albedo with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public boolean apply(JSONSerializer serializer, Object source, String name) {
	if (source == null) {
		return true;
	}

	if (clazz != null && !clazz.isInstance(source)) {
		return true;
	}

	if (this.excludes.contains(name)) {
		return false;
	}

	return includes.size() == 0 || includes.contains(name);
}
 
Example #4
Source File: MyNumberFieldSerializer.java    From dpCms with Apache License 2.0 6 votes vote down vote up
@Override
public void writeValue(JSONSerializer serializer, Object propertyValue) throws Exception {
    SerializeWriter out = serializer.getWriter();

    Object value = propertyValue;

    if (value == null) {
        if (out.isEnabled(SerializerFeature.WriteNullNumberAsZero)) {
            out.write('0');
        } else {
            out.writeNull();
        }
        return;
    }

    out.append(value.toString());
}
 
Example #5
Source File: JsonUtils.java    From feeyo-hlsserver with Apache License 2.0 6 votes vote down vote up
/**
 * 可以允许指定一些过滤字段进行生成json对象
 */
public static String marshalToString(Object obj, String... fliterFields) {
    final List<String> propertyFliters = Arrays.asList(fliterFields);
    SerializeWriter out = new SerializeWriter();
    try {
        JSONSerializer serializer = new JSONSerializer(out);
        serializer.getPropertyFilters().add(new PropertyFilter() {

            public boolean apply(Object source, String name, Object value) {
                return !propertyFliters.contains(name);
            }

        });
        serializer.write(obj);
        return out.toString();
    } finally {
        out.close();
    }
}
 
Example #6
Source File: RbRecordCodec.java    From rebuild with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
    SerializeWriter out = serializer.out;
    if (object == null) {
        out.writeNull();
        return;
    }

    Record record = (Record) object;
    Entity entity = record.getEntity();
    JSONObject map = new JSONObject();
    for (Iterator<String> iter = record.getAvailableFieldIterator(); iter.hasNext(); ) {
        String field = iter.next();
        Object value = record.getObjectValue(field);
        value = FieldValueWrapper.instance.wrapFieldValue(value, entity.getField(field), false);
        map.put(field, value);
    }
    out.write(map.toJSONString());
}
 
Example #7
Source File: ExcludesPropertyPreFilter.java    From java-platform with Apache License 2.0 6 votes vote down vote up
@Override
public boolean apply(JSONSerializer serializer, Object source, String name) {
	if (source == null) {
		return true;
	}

	if (clazz != null && !clazz.isInstance(source)) {
		return true;
	}

	if (excludes.size() == 0 || !excludes.contains(name)) {
		return true;
	}

	return false;
}
 
Example #8
Source File: TreeSerializer.java    From java-platform with Apache License 2.0 6 votes vote down vote up
@Override
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features)
		throws IOException {
	SerializeWriter out = serializer.getWriter();
	if (object == null) {
		out.writeNull();
		return;
	}

	Tree<?> tree = (Tree<?>) object;
	if (tree.isCheckable()) {
		visitCheck(tree.getRoots(), tree.getChecked());
	}

	if (!Strings.isNullOrEmpty(tree.getIconProperty())) {
		visitIcon(tree.getRoots(), tree.getIconProperty());
	}

	if (tree.isExpandAll()) {
		expandAll(tree.getRoots());
	}

	serializer.write(tree.getRoots());
}
 
Example #9
Source File: JsonUtil.java    From dpCms with Apache License 2.0 6 votes vote down vote up
/**
 *  将一个包含Date类型数据的Object序列化成字符串
 * @param object
 * @param dateFormat
 * @param features
 * @return
 */
public static String toJSONStringWithDateFormat(Object object, String dateFormat, SerializerFeature... features) {
       SerializeWriter out = new SerializeWriter();
       try {
           SerializeConfig config = new SerializeConfig();
		JSONSerializer serializer = new JSONSerializer(out,config );
           if(dateFormat != null) {
           	serializer.setDateFormat(dateFormat);
           }
           for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) {
               serializer.config(feature, true);
           }
           serializer.write(object);
           return out.toString();
       } finally {
           out.close();
       }
   }
 
Example #10
Source File: DoubleCustomSerializer.java    From phone with Apache License 2.0 6 votes vote down vote up
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
    SerializeWriter out = serializer.getWriter();

    if (object == null) {
        out.write('0');
        return;
    }

    double doubleValue = ((Double) object).doubleValue();

    if (Double.isNaN(doubleValue)||Double.isInfinite(doubleValue)) {
        out.write('0');
    } else {
        String doubleText = Double.toString(doubleValue);
        NumberUtil.decimal(doubleText, digits, fullZero);
        out.append(doubleText);

        if (serializer.isEnabled(SerializerFeature.WriteClassName)) {
            out.write('D');
        }
    }
}
 
Example #11
Source File: JsonUtils.java    From canal with Apache License 2.0 6 votes vote down vote up
/**
 * 可以允许指定一些过滤字段进行生成json对象
 */
public static String marshalToString(Object obj, String... fliterFields) {
    final List<String> propertyFliters = Arrays.asList(fliterFields);
    SerializeWriter out = new SerializeWriter();
    try {
        JSONSerializer serializer = new JSONSerializer(out);
        serializer.getPropertyFilters().add(new PropertyFilter() {

            public boolean apply(Object source, String name, Object value) {
                return !propertyFliters.contains(name);
            }

        });
        serializer.write(obj);
        return out.toString();
    } finally {
        out.close();
    }
}
 
Example #12
Source File: AbstractResponsePayloadCodec.java    From joyrpc with Apache License 2.0 6 votes vote down vote up
@Override
public void write(final JSONSerializer serializer, final Object object, final Object fieldName,
                  final Type fieldType, final int features) {
    if (object == null) {
        serializer.writeNull();
    } else {
        writeObjectBegin(serializer);
        ResponsePayload payload = (object instanceof ResponseMessage ? ((ResponseMessage<ResponsePayload>) object).getPayLoad() : (ResponsePayload) object);
        if (payload != null) {
            Throwable exception = payload.getException();
            Object response = payload.getResponse();
            if (response != null) {
                write(serializer, RES_CLASS, getTypeName(response, payload.getType()), AFTER);
                write(serializer, RESPONSE, response, NONE);
            } else if (exception != null) {
                write(serializer, RES_CLASS, getCanonicalName(exception.getClass()), AFTER);
                write(serializer, EXCEPTION, exception, NONE);
            }
        }
        writeObjectEnd(serializer);
    }
}
 
Example #13
Source File: HistogramSerializer.java    From watcher with Apache License 2.0 6 votes vote down vote up
@Override
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
	Histogram histogram = (Histogram) object;
	SerializeWriter writer = serializer.getWriter();
	final Snapshot snapshot = histogram.getSnapshot();
	writer.writeFieldValue('{', "count", histogram.getCount());
	writer.writeFieldValue(',', "max", snapshot.getMax());
	writer.writeFieldValue(',', "mean", snapshot.getMean());
	writer.writeFieldValue(',', "min", snapshot.getMin());
	writer.writeFieldValue(',', "p50", snapshot.getMedian());
	writer.writeFieldValue(',', "p75", snapshot.get75thPercentile());
	writer.writeFieldValue(',', "p95", snapshot.get95thPercentile());
	writer.writeFieldValue(',', "p98", snapshot.get98thPercentile());
	writer.writeFieldValue(',', "p99", snapshot.get99thPercentile());
	writer.writeFieldValue(',', "p999", snapshot.get999thPercentile());
	writer.writeFieldValue(',', "stddev", snapshot.getStdDev());
	writer.write('}');
}
 
Example #14
Source File: AbstractInvocationCodec.java    From joyrpc with Apache License 2.0 6 votes vote down vote up
@Override
public void write(final JSONSerializer serializer, final Object object, final Object fieldName, final Type fieldType, final int features) throws IOException {
    if (object == null) {
        serializer.writeNull();
    } else {
        Call call = (Call) object;
        writeObjectBegin(serializer);
        //1、class name
        writeString(serializer, classNameKey, call.getClassName());
        //2、alias
        writeString(serializer, aliasKey, call.getAlias());
        //3、method name
        writeString(serializer, methodNameKey, call.getMethodName());
        //4.argsType
        //TODO 应该根据泛型变量来决定是否要参数类型
        if (call.isCallback()) {
            //回调需要写上实际的参数类型
            write(serializer, argsTypeKey, call.computeArgsType(), AFTER);
        }
        //5、args
        writeArgs(serializer, call);
        //7、attachments
        write(serializer, attachmentsKey, call.getAttachments(), true, BEFORE);
        writeObjectEnd(serializer);
    }
}
 
Example #15
Source File: JsonKit.java    From zbus-server with MIT License 6 votes vote down vote up
private static final byte[] toJSONBytes(Object object, String charsetName,
		SerializerFeature... features) {
	
	if(charsetName == null){
		charsetName = DEFAULT_ENCODING;
	}
	
	SerializeWriter out = new SerializeWriter(); 
	try {
		JSONSerializer serializer = new JSONSerializer(out);
		for (SerializerFeature feature : features) {
			serializer.config(feature, true);
		}

		serializer.write(object);

		return out.toBytes(charsetName);
	} finally {
		out.close();
	}
}
 
Example #16
Source File: JSONPObject.java    From uavstack with Apache License 2.0 6 votes vote down vote up
public void write(JSONSerializer serializer, Object fieldName, Type fieldType, int features) throws IOException {
    SerializeWriter writer = serializer.out;

    if ((features & SerializerFeature.BrowserSecure.mask) != 0
            || (writer.isEnabled(SerializerFeature.BrowserSecure.mask)))
    {
        writer.write(SECURITY_PREFIX);
    }

    writer.write(function);
    writer.write('(');
    for (int i = 0; i < parameters.size(); ++i) {
        if (i != 0) {
            writer.write(',');
        }
        serializer.write(parameters.get(i));
    }
    writer.write(')');
}
 
Example #17
Source File: MappingFastJsonValue.java    From uavstack with Apache License 2.0 6 votes vote down vote up
public void write(JSONSerializer serializer, Object fieldName, Type fieldType, int features) throws IOException {
    SerializeWriter writer = serializer.out;

    if(jsonpFunction == null){
        serializer.write(value);
        return;
    }


    if ((features & BrowserSecureMask) != 0 || (writer.isEnabled(BrowserSecureMask))) {
        writer.write(SECURITY_PREFIX);
    }

    writer.write(jsonpFunction);
    writer.write('(');
    serializer.write(value);
    writer.write(')');
}
 
Example #18
Source File: SimplePropertyPreFilter.java    From talent-aio with GNU Lesser General Public License v2.1 6 votes vote down vote up
public boolean apply(JSONSerializer serializer, Object source, String name)
{
	if (source == null)
	{
		return true;
	}

	if (clazz != null && !clazz.isInstance(source))
	{
		return true;
	}

	if (this.excludes.contains(name))
	{
		return false;
	}

	if (includes.size() == 0 || includes.contains(name))
	{
		return true;
	}

	return false;
}
 
Example #19
Source File: JsonUtils.java    From canal-1.1.3 with Apache License 2.0 6 votes vote down vote up
/**
 * 可以允许指定一些过滤字段进行生成json对象
 */
public static String marshalToString(Object obj, String... fliterFields) {
    final List<String> propertyFliters = Arrays.asList(fliterFields);
    SerializeWriter out = new SerializeWriter();
    try {
        JSONSerializer serializer = new JSONSerializer(out);
        serializer.getPropertyFilters().add(new PropertyFilter() {

            public boolean apply(Object source, String name, Object value) {
                return !propertyFliters.contains(name);
            }

        });
        serializer.write(obj);
        return out.toString();
    } finally {
        out.close();
    }
}
 
Example #20
Source File: FastJsonJodaDateCodec.java    From actframework with Apache License 2.0 6 votes vote down vote up
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
    SerializeWriter out = serializer.getWriter();

    if (object == null) {
        out.writeNull();
        return;
    }

    Class cls = object.getClass();
    if (cls == DateTime.class) {
        out.writeString(dateTimeCodec().toString((DateTime) object));
        return;
    } else if (cls == LocalDateTime.class) {
        out.writeString(localDateTimeCodec().toString((LocalDateTime) object));
        return;
    } else if (cls == LocalDate.class) {
        out.writeString(localDateCodec().toString((LocalDate) object));
        return;
    } else if (cls == LocalTime.class) {
        out.writeString(localTimeCodec().toString((LocalTime) object));
        return;
    }

    out.writeString(object.toString());
}
 
Example #21
Source File: JsonUtils.java    From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 可以允许指定一些过滤字段进行生成json对象
 */
public static String marshalToString(Object obj, String... fliterFields) {
    final List<String> propertyFliters = Arrays.asList(fliterFields);
    SerializeWriter out = new SerializeWriter();
    try {
        JSONSerializer serializer = new JSONSerializer(out);
        serializer.getPropertyFilters().add(new PropertyFilter() {

            public boolean apply(Object source, String name, Object value) {
                return !propertyFliters.contains(name);
            }

        });
        serializer.write(obj);
        return out.toString();
    } finally {
        out.close();
    }
}
 
Example #22
Source File: FastJsonSObjectSerializer.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
    SerializeWriter out = serializer.out;
    if (object instanceof ISObject) {
        ISObject sobj = (ISObject) object;
        out.write(S.fmt("ISObject[%s]", sobj.getKey()));
        return;
    }
    throw new UnsupportedOperationException("Object type not supported: " + object.getClass());
}
 
Example #23
Source File: ResultMarshaller.java    From watcher with Apache License 2.0 5 votes vote down vote up
private JSONSerializer getJsonSerializer(SerializeWriter out) {
	JSONSerializer serializer = new JSONSerializer(out);
	serializer.config(SerializerFeature.WriteDateUseDateFormat, true);
	serializer.setDateFormat("yyyy-MM-dd HH:mm:ss");
	serializer.config(SerializerFeature.QuoteFieldNames, true);
	serializer.config(SerializerFeature.DisableCircularReferenceDetect, true);
	return serializer;
}
 
Example #24
Source File: FastjsonHttpMessageConverter.java    From java-platform with Apache License 2.0 5 votes vote down vote up
@Override
protected void writeInternal(Object obj, Type type, HttpOutputMessage outputMessage)
		throws IOException, HttpMessageNotWritableException {
	Charset charset = getCharset(outputMessage.getHeaders());
	OutputStreamWriter out = new OutputStreamWriter(outputMessage.getBody(), charset);
	SerializeWriter writer = new SerializeWriter(out);
	JSONSerializer serializer = new JSONSerializer(writer, this.serializeConfig);
	serializer.config(SerializerFeature.DisableCircularReferenceDetect, true);

	RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
	if (requestAttributes instanceof ServletRequestAttributes) {
		Class<?> rootClass = filterClass(obj);
		if (rootClass != null) {
			String[] paths = ((ServletRequestAttributes) requestAttributes).getRequest()
					.getParameterValues("paths");
			if (paths != null && paths.length > 0) {
				rootClass = ClassUtils.getUserClass(rootClass);
				Map<Class<?>, PropertyPreFilter> propertyFilters = new HashMap<>();
				pathVisit(propertyFilters, Sets.newHashSet(paths), rootClass);

				for (Entry<Class<?>, PropertyPreFilter> entry : propertyFilters.entrySet()) {
					serializer.getPropertyPreFilters().add(entry.getValue());
				}
			} else {

				serializer.getPropertyFilters().add(DEFAULT_PROPERTY_FILTER);
			}
		} else {
			serializer.getPropertyFilters().add(DEFAULT_PROPERTY_FILTER);
		}
	}
	serializer.write(obj);
	writer.flush();
	out.close();
}
 
Example #25
Source File: MyFieldSerializer.java    From dpCms with Apache License 2.0 5 votes vote down vote up
public void writePrefix(JSONSerializer serializer) throws IOException {
    SerializeWriter out = serializer.getWriter();

    if (serializer.isEnabled(SerializerFeature.QuoteFieldNames)) {
        if (serializer.isEnabled(SerializerFeature.UseSingleQuotes)) {
            out.write(single_quoted_fieldPrefix);
        } else {
            out.write(double_quoted_fieldPrefix);
        }
    } else {
        out.write(un_quoted_fieldPrefix);
    }
}
 
Example #26
Source File: MyListSerializer.java    From dpCms with Apache License 2.0 5 votes vote down vote up
private void handle(JSONSerializer serializer, ObjectSerializer itemSerializer, SerialContext context,
		Object object, Object fieldName, Type elementType,  Object item) throws IOException {
	serializer.println();
	if (item != null) {
		itemSerializer = serializer.getObjectWriter(item.getClass());
		SerialContext itemContext = new SerialContext(context, object, fieldName, 0, 0);
		serializer.setContext(itemContext);
		itemSerializer.write(serializer, item, fieldName, elementType, 0);
	} 
	else {
		serializer.getWriter().writeNull();
	}
}
 
Example #27
Source File: JsonUtil.java    From dpCms with Apache License 2.0 5 votes vote down vote up
/**
 * @see 将一个Object序列化成字符串
 * @param object
 * @param features
 * @return
 */
public static String toJSONString(Object object, SerializerFeature... features) {
       SerializeWriter out = new SerializeWriter();
       try {
           SerializeConfig config = new SerializeConfig();
		JSONSerializer serializer = new JSONSerializer(out,config );
           for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) {
               serializer.config(feature, true);
           }
           serializer.write(object);
           return out.toString();
       } finally {
           out.close();
       }
   }
 
Example #28
Source File: MyJavaBeanSerializer.java    From dpCms with Apache License 2.0 5 votes vote down vote up
@Override
public boolean writeReference(JSONSerializer serializer, Object object,
		int fieldFeatures) {

	SerialContext context = serializer.getContext();
	{

		if (context != null
				&& SerializerFeature.isEnabled(context.getFeatures(),
						fieldFeatures,
						SerializerFeature.DisableCircularReferenceDetect)) {
			return false;
		}
	}

	if (!serializer.containsReference(object)) {
		return false;
	}

	SerialContext parentCtx = context;
	while ((parentCtx = parentCtx.getParent()) != null) {
		Object parentObj = parentCtx.getObject();
		if (object.equals(parentObj)) {
			serializer.writeNull();
			return true;
		}
	}
	return false;
}
 
Example #29
Source File: FastJsonObjectOutput.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public void writeObject(Object obj) throws IOException {
    SerializeWriter out = new SerializeWriter();
    JSONSerializer serializer = new JSONSerializer(out);
    serializer.config(SerializerFeature.WriteEnumUsingToString, true);
    serializer.write(obj);
    out.writeTo(writer);
    writer.println();
    writer.flush();
}
 
Example #30
Source File: EnumDict.java    From hsweb-framework with Apache License 2.0 5 votes vote down vote up
@Override
default void write(JSONSerializer jsonSerializer, Object o, Type type, int i) throws IOException {
    if (isWriteJSONObjectEnabled()) {
        jsonSerializer.write(getWriteJSONObject());
    } else {
        jsonSerializer.write(getValue());
    }
}