下面列出了怎么用com.fasterxml.jackson.core.io.SerializedString的API类实例代码及写法,或者点击链接到github查看源代码。
protected BeanPropertyWriter(BeanPropertyWriter base, SerializedString name) {
super(base);
_name = name;
_wrapperName = base._wrapperName;
_member = base._member;
_contextAnnotations = base._contextAnnotations;
_declaredType = base._declaredType;
_accessorMethod = base._accessorMethod;
_field = base._field;
_serializer = base._serializer;
_nullSerializer = base._nullSerializer;
if (base._internalSettings != null) {
_internalSettings = new HashMap<Object, Object>(
base._internalSettings);
}
_cfgSerializationType = base._cfgSerializationType;
_dynamicSerializers = base._dynamicSerializers;
_suppressNulls = base._suppressNulls;
_suppressableValue = base._suppressableValue;
_includeInViews = base._includeInViews;
_typeSerializer = base._typeSerializer;
_nonTrivialBaseType = base._nonTrivialBaseType;
}
/**
* By default JSON output does only have escaping where it is strictly
* necessary. This is recommended in the most cases. Nevertheless it can
* be sometimes useful to have some more escaping.
*
* @param escapeCharacters an array which defines which characters should be
* escaped and how it will be done. See
* {@link CharacterEscapes}. In most cases this should
* be null. Use like this:
* <pre>{@code int[] esc = CharacterEscapes.standardAsciiEscapesForJSON();
* // and force escaping of a few others:
* esc['\''] = CharacterEscapes.ESCAPE_STANDARD;
* JsonEncoder.useEscapeJavaScript(esc);
* }</pre>
*/
public void setJavaScriptEscapeChars(final int[] escapeCharacters) {
final CharacterEscapes ce = new CharacterEscapes() {
private static final long serialVersionUID = 1L;
@Override
public int[] getEscapeCodesForAscii() {
if (escapeCharacters == null) {
return CharacterEscapes.standardAsciiEscapesForJSON();
}
return escapeCharacters;
}
@Override
public SerializableString getEscapeSequence(final int ch) {
final String jsEscaped = escapeChar((char) ch);
return new SerializedString(jsEscaped);
}
};
jsonGenerator.setCharacterEscapes(ce);
}
/**
* _feature_types : { "featName" : "_ref" or "_byte_array, ... }
*
* @param type the type for which to generate the feature context info
* @throws IOException
*/
private void addJsonFeatContext(TypeImpl type) throws IOException {
final FeatureImpl[] feats = type.getFeatureImpls();
startedFeatureTypes = false;
for (FeatureImpl feat : feats) {
final int fsClass = CasSerializerSupport.classifyType(feat.getRangeImpl());
SerializedString featKind = featureTypeLabel(fsClass);
if (null != featKind) {
maybeDoStartFeatureTypes();
jg.writeFieldName(getSerializedString(feat.getShortName()));
jg.writeString(featKind);
}
}
if (startedFeatureTypes) {
jg.writeEndObject();
}
}
public ObjectFieldJsonExtractor(String fieldName, JsonExtractor<? extends T> delegate, boolean exceptionOnOutOfBounds)
{
this.fieldName = new SerializedString(requireNonNull(fieldName, "fieldName is null"));
this.delegate = requireNonNull(delegate, "delegate is null");
this.exceptionOnOutOfBounds = exceptionOnOutOfBounds;
this.index = tryParseInt(fieldName, -1);
}
/**
* @since 2.5
*/
protected BeanPropertyWriter(BeanPropertyWriter base, PropertyName name) {
super(base);
/*
* 02-Dec-2014, tatu: This is a big mess, alas, what with dependency to
* MapperConfig to encode, and Afterburner having heartburn for
* SerializableString (vs SerializedString). Hope it can be
* resolved/reworked in 2.6 timeframe, if not for 2.5
*/
_name = new SerializedString(name.getSimpleName());
_wrapperName = base._wrapperName;
_contextAnnotations = base._contextAnnotations;
_declaredType = base._declaredType;
_member = base._member;
_accessorMethod = base._accessorMethod;
_field = base._field;
_serializer = base._serializer;
_nullSerializer = base._nullSerializer;
// one more thing: copy internal settings, if any
if (base._internalSettings != null) {
_internalSettings = new HashMap<Object, Object>(
base._internalSettings);
}
_cfgSerializationType = base._cfgSerializationType;
_dynamicSerializers = base._dynamicSerializers;
_suppressNulls = base._suppressNulls;
_suppressableValue = base._suppressableValue;
_includeInViews = base._includeInViews;
_typeSerializer = base._typeSerializer;
_nonTrivialBaseType = base._nonTrivialBaseType;
}
@Override
public UnwrappingBeanPropertyWriter rename(NameTransformer transformer)
{
String oldName = _name.getValue();
String newName = transformer.transform(oldName);
// important: combine transformers:
transformer = NameTransformer.chainedTransformer(transformer, _nameTransformer);
return _new(transformer, new SerializedString(newName));
}
/**
* Factory method called by {@link com.fasterxml.jackson.databind.ser.std.BeanSerializerBase}
* with the initial information based on standard settings for the type
* for which serializer is being built.
*
* @since 2.3
*/
public static ObjectIdWriter construct(JavaType idType, PropertyName propName,
ObjectIdGenerator<?> generator, boolean alwaysAsId)
{
String simpleName = (propName == null) ? null : propName.getSimpleName();
SerializableString serName = (simpleName == null) ? null : new SerializedString(simpleName);
return new ObjectIdWriter(idType, serName, generator, null, alwaysAsId);
}
public GeneratorSettings withRootValueSeparator(String sep) {
if (sep == null) {
if (rootValueSeparator == null) {
return this;
}
return new GeneratorSettings(prettyPrinter, schema, characterEscapes, null);
}
if (sep.equals(_rootValueSeparatorAsString())) {
return this;
}
return new GeneratorSettings(prettyPrinter, schema, characterEscapes,
new SerializedString(sep));
}
public static SerializedString serializeString(String name) {
SerializedString s = new SerializedString(name);
// Eagerly compute encodings.
s.asQuotedChars();
s.asQuotedUTF8();
s.asUnquotedUTF8();
return s;
}
public ObjectFieldJsonExtractor(String fieldName, JsonExtractor<? extends T> delegate, boolean exceptionOnOutOfBounds) {
if (fieldName == null) {
throw new NullPointerException("jsonInput is null");
}
if (delegate == null) {
throw new NullPointerException("delegate is null");
}
this.fieldName = new SerializedString(fieldName);
this.delegate = delegate;
this.exceptionOnOutOfBounds = exceptionOnOutOfBounds;
this.index = tryParseInt(fieldName, -1);
}
public SuperSonicBDBase(BeanDeserializer src,
List<SettableBeanProperty> props)
{
super(src);
final int len = props.size();
_orderedPropertyNames = new SerializedString[len];
for (int i = 0; i < len; ++i) {
_orderedPropertyNames[i] = new SerializedString(props.get(i).getName());
}
// do NOT yet assign properties, they need to be ordered
}
@Override
public void resolve(DeserializationContext ctxt)
throws JsonMappingException
{
super.resolve(ctxt);
// 19-Oct-2017, tatu: Not sure why but seems to occur sometimes...
if (_orderedProperties != null) {
SettableBeanProperty[] oProps = new SettableBeanProperty[6];
SerializedString[] oNames = new SerializedString[6];
int offset = 6 - _propCount;
System.arraycopy(_orderedProperties, 0, oProps, offset, _propCount);
System.arraycopy(_orderedPropertyNames, 0, oNames, offset, _propCount);
_prop1 = oProps[0];
_name1 = oNames[0];
_prop2 = oProps[1];
_name2 = oNames[1];
_prop3 = oProps[2];
_name3 = oNames[2];
_prop4 = oProps[3];
_name4 = oNames[3];
_prop5 = oProps[4];
_name5 = oNames[4];
_prop6 = oProps[5];
_name6 = oNames[5];
}
}
@Override
public SerializableString getEscapeSequence(int aCh)
{
switch (aCh) {
case '\u2028':
return new SerializedString("\\u2028");
case '\u2029':
return new SerializedString("\\u2029");
default:
return null;
}
}
/** Demonstrates how to use a JsonGenerator to stream output that you then persist to the
* server using StringHandle (in this case, implicitly via writeAs).
*/
@Test
public void testWriteStream() throws IOException {
JacksonParserHandle handle = new JacksonParserHandle();
handle = docMgr.read(ORDER_URI, handle);
JsonParser jp = handle.get();
if (jp.nextToken() != JsonToken.START_OBJECT) {
throw new IOException("Expected data to start with an Object");
}
StringWriter jsonWriter = new StringWriter();
JsonGenerator jsonStream = (new ObjectMapper()).getFactory().createGenerator(jsonWriter);
// in this sample case we're copying everything up to and excluding the order
SerializedString order = new SerializedString("order");
do {
jsonStream.copyCurrentEvent(jp);
} while ( ! jp.nextFieldName(order) );
jsonStream.flush();
jsonStream.close();
docMgr.writeAs("testWriteStream.json", jsonWriter.toString());
JsonNode originalTree = docMgr.readAs(ORDER_URI, JsonNode.class);
JsonNode streamedTree = docMgr.readAs("testWriteStream.json", JsonNode.class);
assertEquals("customerName fields don't match",
originalTree.get("customerName"), streamedTree.get("customerName"));
assertEquals("shipToAddress fields don't match",
originalTree.get("shipToAddress"), streamedTree.get("shipToAddress"));
assertEquals("billingAddressRequired fields don't match",
originalTree.get("billingAddressRequired"), streamedTree.get("billingAddressRequired"));
}
public BeanPropertyWriter(int typeId, String n, Field f, Method getter)
{
this.typeId = typeId;
name = new SerializedString(n);
if ((getter == null) && (f == null)) {
throw new IllegalArgumentException("Missing getter and field");
}
_field = f;
_getter = getter;
}
private SerializedString getSerializedTypeName(TypeImpl ti) {
XmlElementName xe = cds.typeCode2namespaceNames[ti.getCode()];
if (null == xe) {
// happens for supertypes which have no instantiations
String typeName = ti.getName();
xe = uimaTypeName2XmiElementName(typeName);
checkForNameCollision(xe);
cds.typeCode2namespaceNames[ti.getCode()] = xe;
}
return getSerializedString(xe.qName);
}
/**
* Return null or a string representing the type of the feature
*
*
* @param fsClass the class of the feature
* @param featCode the feature code
* @return _ref, _array, _byte_array, or null
*/
private SerializedString featureTypeLabel(int fsClass) {
switch (fsClass) {
case LowLevelCAS.TYPE_CLASS_FS:
case LowLevelCAS.TYPE_CLASS_FSARRAY:
case CasSerializerSupport.TYPE_CLASS_FSLIST:
return FEATURE_REFS_NAME;
case LowLevelCAS.TYPE_CLASS_INTARRAY:
case LowLevelCAS.TYPE_CLASS_FLOATARRAY:
case LowLevelCAS.TYPE_CLASS_STRINGARRAY:
case LowLevelCAS.TYPE_CLASS_BOOLEANARRAY:
case LowLevelCAS.TYPE_CLASS_SHORTARRAY:
case LowLevelCAS.TYPE_CLASS_LONGARRAY:
case LowLevelCAS.TYPE_CLASS_DOUBLEARRAY:
case CasSerializerSupport.TYPE_CLASS_INTLIST:
case CasSerializerSupport.TYPE_CLASS_FLOATLIST:
case CasSerializerSupport.TYPE_CLASS_STRINGLIST:
// we have refs only if the feature has
// multipleReferencesAllowed = true
return FEATURE_ARRAY_NAME;
case LowLevelCAS.TYPE_CLASS_BYTEARRAY:
return FEATURE_BYTE_ARRAY_NAME;
default: // for primitives
return null;
}
}
protected UnwrappingBeanPropertyWriter(UnwrappingBeanPropertyWriter base, NameTransformer transformer,
SerializedString name) {
super(base, name);
_nameTransformer = transformer;
}
/**
* @since 2.6.0
*/
public DefaultPrettyPrinter withRootSeparator(String rootSeparator) {
return withRootSeparator((rootSeparator == null) ? null : new SerializedString(rootSeparator));
}
protected GuavaUnwrappingOptionalBeanPropertyWriter(UnwrappingBeanPropertyWriter base,
NameTransformer transformer, SerializedString name) {
super(base, transformer, name);
}
@Override
protected UnwrappingBeanPropertyWriter _new(NameTransformer transformer, SerializedString newName)
{
return new GuavaUnwrappingOptionalBeanPropertyWriter(this, transformer, newName);
}
@Override
public SerializableString getEscapeSequence(int ch) {
return new SerializedString("\\u" + String.format("%04x", ch));
}
/**
* @since 2.6.0
*/
public DefaultPrettyPrinter withRootSeparator(String rootSeparator) {
return withRootSeparator((rootSeparator == null) ? null : new SerializedString(rootSeparator));
}
public JacksonService() {
// fun Jackson API with circular dependencies ... so we create a mapper
// first, and grab implicitly created factory from it
this.sharedMapper = new ObjectMapper();
this.sharedFactory = sharedMapper.getFactory();
final SerializableString LINE_SEPARATOR = new SerializedString("\\u2028");
final SerializableString PARAGRAPH_SEPARATOR = new SerializedString("\\u2029");
this.sharedFactory.setCharacterEscapes(new CharacterEscapes() {
private static final long serialVersionUID = 3995801066651016289L;
@Override
public int[] getEscapeCodesForAscii() {
return standardAsciiEscapesForJSON();
}
@Override
public SerializableString getEscapeSequence(int ch) {
// see ECMA-262 Section 7.3;
// in most cases our client is browser,
// and JSON is parsed into JS;
// therefore these two whitespace characters,
// which are perfectly valid in JSON but invalid in JS strings,
// need to be escaped...
switch (ch) {
case '\u2028':
return LINE_SEPARATOR;
case '\u2029':
return PARAGRAPH_SEPARATOR;
default:
return null;
}
}
});
// make sure mapper does not attempt closing streams it does not
// manage... why is this even a default in jackson?
sharedFactory.disable(Feature.AUTO_CLOSE_TARGET);
// do not flush every time. why would we want to do that?
// this is having a HUGE impact on extrest serializers (5x speedup)
sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE);
}
protected void writeNullField(SerializedString fieldName) throws IOException {
if (_writeNullValues) {
_generator.writeFieldName(fieldName);
_generator.writeNull();
}
}
private void writeViewForDeltas(SerializedString kind, Collection<TOP> deltaMembers) throws IOException {
jg.writeFieldName(kind);
jg.writeStartArray();
writeViewMembers(deltaMembers);
jg.writeEndArray();
}
private SerializedString getShortFeatureName(FeatureImpl feat) {
return getSerializedString(feat.getShortName());
}
private void writeFsOrLists(TOP fs, TypeImpl ti, boolean isListAsFSs) throws IOException {
final FeatureImpl[] feats = ti.getFeatureImpls();
// maybeWriteIdFeat(addr);
maybeWriteTypeFeat(ti);
for (final FeatureImpl feat : feats) {
if (cds.isFiltering) {
// skip features that aren't in the target type system
String fullFeatName = feat.getName();
if (cds.filterTypeSystem_inner.getFeatureByFullName(fullFeatName) == null) {
continue;
}
}
// final int featAddr = addr + cds.cas.getAdjustedFeatureOffset(featCode);
// final int featValRaw = cds.cas.getHeapValue(featAddr);
final int featureClass = CasSerializerSupport.classifyType(feat.getRangeImpl());
final SerializedString shortName = getSerializedString(feat.getShortName());
switch (featureClass) {
case LowLevelCAS.TYPE_CLASS_BYTE: writeNumeric(feat, fs._getByteValueNc (feat)); break;
case LowLevelCAS.TYPE_CLASS_SHORT: writeNumeric(feat, fs._getShortValueNc(feat)); break;
case LowLevelCAS.TYPE_CLASS_INT: writeNumeric(feat, fs._getIntValueNc (feat)); break;
case LowLevelCAS.TYPE_CLASS_LONG: writeNumeric(feat, fs._getLongValueNc (feat)); break;
case LowLevelCAS.TYPE_CLASS_FS: {
TOP ref = fs._getFeatureValueNc(feat);
if (ref == null /* && isOmitDefaultValues*/) continue;
writeFsOrRef(ref, feat); // writes nl before embedded fs
break;
}
case LowLevelCAS.TYPE_CLASS_FLOAT:
final float floatVal = fs._getFloatValueNc(feat);
if (floatVal == 0.F && isOmitDefaultValues) continue;
jg.writeFieldName(shortName);
jg.writeNumber(floatVal);
break;
case LowLevelCAS.TYPE_CLASS_DOUBLE:
final double doubleVal = fs._getDoubleValueNc(feat);
if (doubleVal == 0L && isOmitDefaultValues) continue;
jg.writeFieldName(shortName);
jg.writeNumber(doubleVal);
break;
case LowLevelCAS.TYPE_CLASS_BOOLEAN:
jg.writeFieldName(shortName);
jg.writeBoolean(fs._getBooleanValueNc(feat));
break;
case LowLevelCAS.TYPE_CLASS_STRING: {
String s = fs._getStringValueNc(feat);
if (s == null /*&& isOmitDefaultValues*/) continue;
jg.writeFieldName(shortName);
jg.writeString(s);
break;
}
case LowLevelCAS.TYPE_CLASS_INTARRAY:
case LowLevelCAS.TYPE_CLASS_FLOATARRAY:
case LowLevelCAS.TYPE_CLASS_BOOLEANARRAY:
case LowLevelCAS.TYPE_CLASS_BYTEARRAY:
case LowLevelCAS.TYPE_CLASS_SHORTARRAY:
case LowLevelCAS.TYPE_CLASS_LONGARRAY:
case LowLevelCAS.TYPE_CLASS_DOUBLEARRAY:
case LowLevelCAS.TYPE_CLASS_STRINGARRAY:
case LowLevelCAS.TYPE_CLASS_FSARRAY:
writeArray(fs, feat, featureClass);
break;
case CasSerializerSupport.TYPE_CLASS_INTLIST:
case CasSerializerSupport.TYPE_CLASS_FLOATLIST:
case CasSerializerSupport.TYPE_CLASS_STRINGLIST:
case CasSerializerSupport.TYPE_CLASS_FSLIST:
writeList(fs, feat, featureClass, isListAsFSs);
break;
default: Misc.internalError();
} // end of switch
} // end of loop over all features
}
/**
* Method for constructing a specialized textual object that can typically
* be serialized faster than basic {@link java.lang.String} (depending
* on escaping needed if any, char-to-byte encoding if needed).
*
* @param src Text to represent
*
* @return Optimized text object constructed
*
* @since 2.4
*/
public SerializableString compileString(String src) {
/* 20-Jan-2014, tatu: For now we will just construct it directly, but
* for 2.4 need to allow overriding to support non-standard extensions
* to be used by extensions like Afterburner.
*/
return new SerializedString(src);
}
/**
* Overridable factory method used by sub-classes
*
* @since 2.6.0
*/
protected UnwrappingBeanPropertyWriter _new(NameTransformer transformer, SerializedString newName)
{
return new UnwrappingBeanPropertyWriter(this, transformer, newName);
}