com.alibaba.fastjson.serializer.SerializeWriter Java Examples

The following examples show how to use com.alibaba.fastjson.serializer.SerializeWriter. 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: 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 #2
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 #3
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 #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: 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 #6
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 #7
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 #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: 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 #10
Source File: TimerSerializer.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 {
	Timer timer = (Timer) object;
	final Snapshot snapshot = timer.getSnapshot();
	SerializeWriter writer = serializer.getWriter();
	writer.writeFieldValue('{', "count", timer.getCount());
	writer.writeFieldValue(',', "max", snapshot.getMax() * durationFactor);
	writer.writeFieldValue(',', "mean", snapshot.getMean() * durationFactor);
	writer.writeFieldValue(',', "min", snapshot.getMin() * durationFactor);
	
	writer.writeFieldValue(',', "p50", snapshot.getMedian() * durationFactor);
	writer.writeFieldValue(',', "p75", snapshot.get75thPercentile() * durationFactor);
	writer.writeFieldValue(',', "p95", snapshot.get95thPercentile() * durationFactor);
	writer.writeFieldValue(',', "p98", snapshot.get98thPercentile() * durationFactor);
	writer.writeFieldValue(',', "p99", snapshot.get99thPercentile() * durationFactor);
	writer.writeFieldValue(',', "p999", snapshot.get999thPercentile() * durationFactor);
	
	writer.writeFieldValue(',', "stddev", snapshot.getStdDev() * durationFactor);
	writer.writeFieldValue(',', "m15_rate", timer.getFifteenMinuteRate() * rateFactor);
	writer.writeFieldValue(',', "m1_rate", timer.getOneMinuteRate() * rateFactor);
	writer.writeFieldValue(',', "m5_rate", timer.getFiveMinuteRate() * rateFactor);
	writer.writeFieldValue(',', "mean_rate", timer.getMeanRate() * rateFactor);
	writer.writeFieldValue(',', "duration_units", durationUnit);
	writer.writeFieldValue(',', "rate_units", rateUnit);
	writer.write('}');
}
 
Example #11
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 #12
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 #13
Source File: JsonUtils.java    From arthas with Apache License 2.0 6 votes vote down vote up
/**
 * Set Fastjson SerializeWriter ThreadLocal value
 */
public static void setSerializeWriterBufThreadLocal(char[] charsBuf, byte[] bytesBuf) {
    Class<SerializeWriter> clazz = SerializeWriter.class;
    try {
        //set threadLocal value
        if (serializeWriterBufLocalField == null) {
            serializeWriterBufLocalField = clazz.getDeclaredField("bufLocal");
        }
        serializeWriterBufLocalField.setAccessible(true);
        ThreadLocal<char[]> bufLocal = (ThreadLocal<char[]>) serializeWriterBufLocalField.get(null);
        bufLocal.set(charsBuf);

        if (serializeWriterBytesBufLocal == null) {
            serializeWriterBytesBufLocal = clazz.getDeclaredField("bytesBufLocal");
        }
        serializeWriterBytesBufLocal.setAccessible(true);
        ThreadLocal<byte[]> bytesBufLocal = (ThreadLocal<byte[]>) serializeWriterBytesBufLocal.get(null);
        bytesBufLocal.set(bytesBuf);
    } catch (Throwable e) {
        logger.error("update SerializeWriter.BUFFER_THRESHOLD value failed", e);
    }
}
 
Example #14
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 #15
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 #16
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 #17
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 #18
Source File: FastJsonIssue.java    From actframework 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
) {
    SerializeWriter out = serializer.getWriter();
    if (object == null) {
        out.writeNull();
    } else {
        Class cls = object.getClass();
        if (cls == DateTime.class) {
            out.writeString(object.toString());
        } else {
            out.writeString(object.toString());
        }
    }
}
 
Example #19
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 #20
Source File: AbstractSerializer.java    From joyrpc with Apache License 2.0 6 votes vote down vote up
/**
 * 写值
 *
 * @param out        输出
 * @param field      字段
 * @param value      值
 * @param ignoreNull 是否忽略null值
 * @param separator  分隔符位置
 */
protected void writeString(final SerializeWriter out, final String field, final String value,
                           final boolean ignoreNull, final int separator) {
    if (value != null || !ignoreNull) {
        if (separator == BEFORE) {
            out.write(',');
        }
        out.writeFieldName(field);
        if (value == null) {
            out.writeNull();
        } else {
            out.writeString(value);
        }
        if (separator == AFTER) {
            out.write(',');
        }
    }
}
 
Example #21
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 #22
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 #23
Source File: BigDecimalCustomSerializer.java    From phone with Apache License 2.0 5 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;
    }

    BigDecimal val = (BigDecimal) object;
    String value = val.toString();
    out.write(NumberUtil.decimal(value, digits, fullZero));
    if (out.isEnabled(SerializerFeature.WriteClassName) && fieldType != BigDecimal.class && val.scale() == 0) {
        out.write('.');
    }
}
 
Example #24
Source File: PageSerializer.java    From java-platform 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.getWriter();
	if (object == null) {
		out.writeNull();
		return;
	}

	Page<?> page = (Page<?>) object;

	out.write('{');

	out.writeFieldName(DEFAULT_CURRENT_FIELD);
	out.writeInt(page.getNumber());
	out.write(',');

	out.writeFieldName(DEFAULT_ROWCOUNT_FIELD);
	out.writeInt(page.getSize());
	out.write(',');

	out.writeFieldName(DEFAULT_TOTAL_FIELD);
	out.writeLong(page.getTotalElements());
	out.write(',');

	out.writeFieldName(DEFAULT_ROWS_FIELD);
	serializer.write(page.getContent());

	out.write('}');
}
 
Example #25
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 #26
Source File: AjaxAuthenticationFilter.java    From java-platform with Apache License 2.0 5 votes vote down vote up
protected void writeObject(ServletRequest request, ServletResponse response, Object result) throws IOException {
	String characterEncoding = ((HttpServletRequest) request).getCharacterEncoding();
	Charset charset = Strings.isNullOrEmpty(characterEncoding) ? DEFAULT_CHARSET : Charset.forName(characterEncoding);
	OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream(), charset);
	SerializeWriter writer = new SerializeWriter(out);
	JSONSerializer serializer = new JSONSerializer(writer, SpringContext.getBean(SerializeConfig.class));
	serializer.config(SerializerFeature.DisableCircularReferenceDetect, true);
	serializer.write(result);
	writer.flush();
	out.close();
}
 
Example #27
Source File: CaptchaFilter.java    From java-platform with Apache License 2.0 5 votes vote down vote up
protected void writeObject(ServletRequest request, ServletResponse response, Object result) throws IOException {
	String characterEncoding = ((HttpServletRequest) request).getCharacterEncoding();
	Charset charset = Strings.isNullOrEmpty(characterEncoding) ? DEFAULT_CHARSET
			: Charset.forName(characterEncoding);
	OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream(), charset);
	SerializeWriter writer = new SerializeWriter(out);
	JSONSerializer serializer = new JSONSerializer(writer, this.serializeConfig);
	serializer.config(SerializerFeature.DisableCircularReferenceDetect, true);
	serializer.write(result);
	writer.flush();
	out.close();
}
 
Example #28
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 #29
Source File: FastJsonFileSerializer.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 File) {
        File file = (File) object;
        out.write(S.fmt("File[%s]", file.getPath()));
        return;
    }
    throw new UnsupportedOperationException("Object type not supported: " + object.getClass());
}
 
Example #30
Source File: JodaDateTimeSerializer.java    From java-platform 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.getWriter();
	if (object == null) {
		out.writeNull();
		return;
	}

	DateTime dateTime = (DateTime) object;
	serializer.write(dateTime.toDate());
}