Java Code Examples for com.alibaba.fastjson.serializer.SerializeWriter#write()

The following examples show how to use com.alibaba.fastjson.serializer.SerializeWriter#write() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
Source File: GaugeSerializer.java    From watcher 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 {
	Gauge gauge = (Gauge) object;
	Object value = gauge.getValue();
	SerializeWriter writer = serializer.getWriter();
	if (value == null)
		writer.write("0");
	else
		writer.write(value.toString());
}
 
Example 10
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 11
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 12
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 13
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 14
Source File: MeterSerializer.java    From watcher 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 {
	Meter meter = (Meter) object;
	SerializeWriter writer = serializer.getWriter();
	writer.writeFieldValue('{', "count", meter.getCount());
	writer.writeFieldValue(',', "m15_rate", meter.getFifteenMinuteRate() * rateFactor);
	writer.writeFieldValue(',', "m1_rate", meter.getOneMinuteRate() * rateFactor);
	writer.writeFieldValue(',', "m5_rate", meter.getFiveMinuteRate() * rateFactor);
	writer.writeFieldValue(',', "mean_rate", meter.getMeanRate() * rateFactor);
	writer.writeFieldValue(',', "units", rateUnit);
	writer.write('}');
}
 
Example 15
Source File: BaseOperationAdapter.java    From java-unified-sdk 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 {
  BaseOperation op = (BaseOperation)object;
  SerializeWriter writer = serializer.getWriter();
  writer.write('{');
  writer.writeFieldValue(' ', ATTR_OP, op.getOperation());
  writer.writeFieldValue(' ', ATTR_FIELD, op.getField());
  writer.writeFieldValue(',', ATTR_FINAL, op.isFinal);
  if (AVOSCloud.isEnableCircularReferenceDetect()) {
    writer.writeFieldValue(',', ATTR_OBJECT,
            JSON.toJSONString(op.getValue(), ObjectValueFilter.instance,
                    SerializerFeature.WriteClassName));
  } else {
    writer.writeFieldValue(',', ATTR_OBJECT,
            JSON.toJSONString(op.getValue(), ObjectValueFilter.instance,
                    SerializerFeature.WriteClassName, SerializerFeature.DisableCircularReferenceDetect));
  }

  if (object instanceof CompoundOperation) {
    if (AVOSCloud.isEnableCircularReferenceDetect()) {
      writer.writeFieldValue(',', ATTR_SUBOPS,
              JSON.toJSONString(((CompoundOperation)op).getSubOperations(), ObjectValueFilter.instance,
                      SerializerFeature.WriteClassName));
    } else {
      writer.writeFieldValue(',', ATTR_SUBOPS,
              JSON.toJSONString(((CompoundOperation)op).getSubOperations(), ObjectValueFilter.instance,
                      SerializerFeature.WriteClassName, SerializerFeature.DisableCircularReferenceDetect));
    }
  }
  writer.write('}');
}
 
Example 16
Source File: FastJsonValueObjectSerializer.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.getWriter();
    if (object == null) {
        out.writeNull();
        return;
    }
    ValueObject vo = (ValueObject) object;
    out.write(vo.toJSONString());
}
 
Example 17
Source File: AbstractSerializer.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
/**
 * 写值
 *
 * @param serializer 输出
 * @param field      字段
 * @param value      值
 * @param ignoreNull 是否忽略null值
 * @param separator  分隔符位置
 */
protected void write(final JSONSerializer serializer, final String field, final Object value,
                     final boolean ignoreNull, final int separator) {
    if (value != null || !ignoreNull) {
        SerializeWriter out = serializer.getWriter();
        if (separator == BEFORE) {
            out.write(',');
        }
        out.writeFieldName(field);
        serializer.write(value);
        if (separator == AFTER) {
            out.write(',');
        }
    }
}
 
Example 18
Source File: MyCollectionSerializer.java    From dpCms with Apache License 2.0 4 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) {
        if (out.isEnabled(SerializerFeature.WriteNullListAsEmpty)) {
            out.write("[]");
        } 
        else {
            out.writeNull();
        }
        return;
    }

    Type elementType = null;
    if (serializer.isEnabled(SerializerFeature.WriteClassName)) {
        if (fieldType instanceof ParameterizedType) {
            ParameterizedType param = (ParameterizedType) fieldType;
            elementType = param.getActualTypeArguments()[0];
        }
    }

    Collection<?> collection = (Collection<?>) object;

    SerialContext context = serializer.getContext();
    serializer.setContext(context, object, fieldName, 0);

    if (serializer.isEnabled(SerializerFeature.WriteClassName)) {
        if (HashSet.class == collection.getClass()) {
            out.append("Set");
        } 
        else if (TreeSet.class == collection.getClass()) {
            out.append("TreeSet");
        }
    }

    try {
        int i = 0;
        out.append('[');
        
        for (Object item : collection) {

            if (i++ != 0) {
                out.append(',');
            }

            if (item == null) {
                out.writeNull();
                continue;
            }

            Class<?> clazz = item.getClass();

            if (clazz == Integer.class) {
                out.writeInt(((Integer) item).intValue());
                continue;
            }

            if (clazz == Long.class) {
                out.writeLong(((Long) item).longValue());

                if (out.isEnabled(SerializerFeature.WriteClassName)) {
                    out.write('L');
                }
                continue;
            }

            ObjectSerializer itemSerializer = serializer.getObjectWriter(clazz);
            itemSerializer.write(serializer, item, i - 1, elementType, 0);
        }
        out.append(']');
    } 
    finally {
        serializer.setContext(context);
    }
}
 
Example 19
Source File: NodeSerializer.java    From java-platform with Apache License 2.0 4 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;
	}

	Node<?> node = (Node<?>) object;

	out.write('{');

	out.writeFieldName("children");
	serializer.write(node.getChildren());
	out.write(",");

	out.writeFieldName("leaf");
	out.write(node.getLeaf());
	out.write(",");

	if (!Strings.isNullOrEmpty(node.getIcon())) {
		out.writeFieldName("icon");
		out.writeString(node.getIcon());
		out.write(",");
	}

	if (node.getChecked() != null) {
		out.writeFieldName("checked");
		out.write(node.getChecked());
		out.write(",");
	}

	if (node.getExpanded() != null) {
		out.writeFieldName("expanded");
		out.write(node.getExpanded());
		out.write(",");
	}

	List<? extends SerializeFilter> serializeFilters = serializer.getPropertyPreFilters();

	Object data = node.getData();

	// 处理父节点
	if (data != null && data instanceof Treeable && serializeFilters != null && serializeFilters.size() > 0) {
		boolean parentProcess = false;
		for (SerializeFilter filter : serializeFilters) {
			if (filter instanceof IncludesPropertyPreFilter) {
				Set<String> includes = ((IncludesPropertyPreFilter) filter).getIncludes();
				parentProcess = includes.contains("parent");
				if (parentProcess) {
					break;
				}
			}
		}
		if (parentProcess) {
			Object parent = ((Treeable<?>) data).getParent();
			if (parent != null) {
				out.writeFieldName("parent");
				out.write(JSON.toJSONString(parent, serializeConfig,
						Iterables.toArray(serializeFilters, SerializeFilter.class)));
				out.write(",");
			}
		}
	}

	// 处理对象值
	String dataString = serializeFilters == null ? JSON.toJSONString(data, serializeConfig)
			: JSON.toJSONString(data, serializeConfig, Iterables.toArray(serializeFilters, SerializeFilter.class));
	dataString = StringUtils.substring(dataString, 1);
	out.write(dataString);
}
 
Example 20
Source File: ResultSerializer.java    From java-platform with Apache License 2.0 4 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;
	}

	Result result = (Result) object;

	out.write('{');

	Map<String, Object> extraProperties = result.getExtraProperties();
	for (Entry<String, Object> entry : extraProperties.entrySet()) {
		String key = entry.getKey();
		Object value = entry.getValue();

		out.writeFieldName(key);
		serializer.write(value);
		out.write(',');
	}

	out.writeFieldName(FIELD_SUCCESS);
	out.write(Objects.equal(result.getCode(), Code.success));
	out.write(',');

	out.writeFieldName(FIELD_CODE);
	out.writeString(result.getCode().name());
	out.write(',');

	out.writeFieldName(FIELD_MESSAGE);
	out.writeString(result.getMessage());
	out.write(',');

	out.writeFieldName(FIELD_DATA);
	serializer.write(result.getData());

	out.write('}');
}