com.fasterxml.jackson.databind.DeserializationContext源码实例Demo

类com.fasterxml.jackson.databind.DeserializationContext源码实例Demo

下面列出了com.fasterxml.jackson.databind.DeserializationContext 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: incubator-pinot   文件: ColumnPartitionMetadata.java
@Override
public ColumnPartitionMetadata deserialize(JsonParser p, DeserializationContext ctxt)
    throws IOException {
  JsonNode jsonMetadata = p.getCodec().readTree(p);
  Set<Integer> partitions = new HashSet<>();
  JsonNode jsonPartitions = jsonMetadata.get(PARTITIONS_KEY);
  if (jsonPartitions != null) {
    // Integer format: "partitions":[0,1,5]
    for (JsonNode jsonPartition : jsonPartitions) {
      partitions.add(jsonPartition.asInt());
    }
  } else {
    // Legacy format: "partitionRanges":"[0 1],[5 5]"
    String partitionRanges = jsonMetadata.get(LEGACY_PARTITIONS_KEY).asText();
    for (String partitionRange : StringUtils.split(partitionRanges, LEGACY_PARTITION_DELIMITER)) {
      addRangeToPartitions(partitionRange, partitions);
    }
  }
  return new ColumnPartitionMetadata(jsonMetadata.get(FUNCTION_NAME_KEY).asText(),
      jsonMetadata.get(NUM_PARTITIONS_KEY).asInt(), partitions);
}
 
源代码2 项目: caravan   文件: CustomCollectionDeserializer.java
@SuppressWarnings("unchecked")
@Override
public Object deserialize(JsonParser p, DeserializationContext ctxt)
    throws IOException {
  if (_delegateDeserializer != null) {
    return (Collection<Object>) _valueInstantiator.createUsingDelegate(ctxt,
        _delegateDeserializer.deserialize(p, ctxt));
  }
  // Empty String may be ok; bit tricky to check, however, since
  // there is also possibility of "auto-wrapping" of single-element arrays.
  // Hence we only accept empty String here.
  if (p.hasToken(JsonToken.VALUE_STRING)) {
    String str = p.getText();
    if (str.length() == 0) {
      return (Collection<Object>) _valueInstantiator.createFromString(ctxt, str);
    }
  }
  return deserialize(p, ctxt, createDefaultInstance(ctxt));
}
 
源代码3 项目: roboconf-platform   文件: JSonBindingUtils.java
@Override
public TargetWrapperDescriptor deserialize( JsonParser parser, DeserializationContext context ) throws IOException {

	ObjectCodec oc = parser.getCodec();
	JsonNode node = oc.readTree( parser );
	TargetWrapperDescriptor twd = new TargetWrapperDescriptor();

	JsonNode n;
	if(( n = node.get( DESC )) != null )
		twd.setDescription( n.textValue());

	if(( n = node.get( TARGET_HANDLER )) != null )
		twd.setHandler( n.textValue());

	if(( n = node.get( ID )) != null )
		twd.setId( n.textValue());

	if(( n = node.get( NAME )) != null )
		twd.setName( n.textValue());

	return twd;
}
 
源代码4 项目: logging-log4j2   文件: ContextDataDeserializer.java
@Override
    public StringMap deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException,
            JsonProcessingException {

        // Sanity check: verify that we got "Json Object":
//        JsonToken tok = jp.nextToken();
//        if (tok != JsonToken.START_OBJECT) {
//            throw new IOException("Expected data to start with an Object");
//        }
        final StringMap contextData = ContextDataFactory.createContextData();
        // Iterate over object fields:
        while (jp.nextToken() != JsonToken.END_OBJECT) {
            final String fieldName = jp.getCurrentName();

            // move to value
            jp.nextToken();
            contextData.putValue(fieldName, jp.getText());
        }
        return contextData;
    }
 
@Override
public DeviceRenderTypeMap deserialize( JsonParser jsonParser, DeserializationContext deserializationContext )
    throws IOException
{
    DeviceRenderTypeMap<T>  deviceRenderTypeMap = new DeviceRenderTypeMap<>();
    LinkedHashMap<String, LinkedHashMap<String,String>> map = jsonParser
        .readValueAs( new TypeReference<LinkedHashMap<String, LinkedHashMap<String,String>>>() {} );

    for( String renderDevice : map.keySet() )
    {
        LinkedHashMap<String,String> renderObjectMap = map.get( renderDevice );
        T renderingObject = serializeObject.get();
        renderingObject.setType( Enum.valueOf( renderingObject.getRenderTypeClass(), renderObjectMap.get( RenderingObject._TYPE ) ) );
        deviceRenderTypeMap.put( RenderDevice.valueOf( renderDevice ), renderingObject );
    }

    return deviceRenderTypeMap;
}
 
@Override
public SourceForgeSearchResult deserialize(JsonParser parser,
        DeserializationContext context) throws IOException,
        JsonProcessingException {
    ObjectCodec oc = parser.getCodec();
    JsonNode node = oc.readTree(parser);

    SourceForgeSearchResult result = new SourceForgeSearchResult();

    result.setCount(node.get("count").asInt());

    Iterator<JsonNode> tickets = node.path("tickets").iterator();
    while (tickets.hasNext()) {
        JsonNode ticket = tickets.next();
        result.addTicketId(ticket.get("ticket_num").asInt());
    }

    return result;
}
 
源代码7 项目: KaiZen-OpenAPI-Editor   文件: NodeDeserializer.java
protected ObjectNode deserializeObjectNode(JsonParser p, DeserializationContext context, JsonLocation startLocation)
        throws IllegalArgumentException, IOException {

    final Model model = (Model) context.getAttribute(ATTRIBUTE_MODEL);
    final AbstractNode parent = (AbstractNode) context.getAttribute(ATTRIBUTE_PARENT);
    final JsonPointer ptr = (JsonPointer) context.getAttribute(ATTRIBUTE_POINTER);

    final ObjectNode node = model.objectNode(parent, ptr);
    node.setStartLocation(createLocation(startLocation));

    while (p.nextToken() != JsonToken.END_OBJECT) {
        String name = p.getCurrentName();

        JsonPointer pp = JsonPointer.compile(ptr.toString() + "/" + name.replaceAll("/", "~1"));
        context.setAttribute(ATTRIBUTE_PARENT, node);
        context.setAttribute(ATTRIBUTE_POINTER, pp);

        AbstractNode v = deserialize(p, context);
        v.setProperty(name);
        node.put(name, v);
    }

    node.setEndLocation(createLocation(p.getCurrentLocation()));
    return node;
}
 
源代码8 项目: lams   文件: JavaUtilCollectionsDeserializers.java
public static JsonDeserializer<?> findForMap(DeserializationContext ctxt,
        JavaType type)
    throws JsonMappingException
{
    JavaUtilCollectionsConverter conv;

    // 10-Jan-2017, tatu: Some types from `java.util.Collections`/`java.util.Arrays` need bit of help...
    if (type.hasRawClass(CLASS_SINGLETON_MAP)) {
        conv = converter(TYPE_SINGLETON_MAP, type, Map.class);
    } else if (type.hasRawClass(CLASS_UNMODIFIABLE_MAP)) {
        conv = converter(TYPE_UNMODIFIABLE_MAP, type, Map.class);
    } else {
        return null;
    }
    return new StdDelegatingDeserializer<Object>(conv);
}
 
源代码9 项目: td-ameritrade-client   文件: MiscTest.java
@Test
public void testNanDeserializer() throws IOException {
  ObjectMapper mapper = new ObjectMapper();
  String json = "{ \"theta\":  \"NAN\"}";

  try (InputStream stream = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8))){
    JsonParser parser = mapper.getFactory().createParser(stream);
    DeserializationContext ctxt = mapper.getDeserializationContext();
    BigDecimalNanDeserializer deserializer = new BigDecimalNanDeserializer();
    parser.nextToken();
    parser.nextToken();
    parser.nextToken();

    final BigDecimal deserialized = deserializer.deserialize(parser, ctxt);
    LOGGER.debug("NAN -> {}", deserialized);
    assertThat(deserialized).isEqualTo("0");
  }
}
 
@Override
protected MetadataRequest doRequestDeserialize(JsonParser jparser, DeserializationContext ctxt, FederatedIdentity identity, String queryId, String catalogName)
        throws IOException
{
    assertFieldName(jparser, TABLE_NAME_FIELD);
    TableName tableName = tableNameDeserializer.deserialize(jparser, ctxt);

    assertFieldName(jparser, CONSTRAINTS_FIELD);
    Constraints constraints = constraintsDeserializer.deserialize(jparser, ctxt);

    assertFieldName(jparser, SCHEMA_FIELD);
    Schema schema = schemaDeserializer.deserialize(jparser, ctxt);

    ImmutableSet.Builder<String> partitionColsSet = ImmutableSet.builder();
    partitionColsSet.addAll(getNextStringArray(jparser, PARTITION_COLS_FIELD));

    return new GetTableLayoutRequest(identity, queryId, catalogName, tableName, constraints, schema, partitionColsSet.build());
}
 
@Override
public Date deserialize(final JsonParser parser, final DeserializationContext context) throws IOException
{
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");

    final String date = parser.getText();
    try
    {
        return formatter.parse(date);
    }
    catch (final ParseException ex)
    {
        // Not worked, so let the default date serializer give it a try.
        return DateDeserializer.instance.deserialize(parser, context);
    }
}
 
源代码12 项目: Partner-Center-Java   文件: ArtifactDeserializer.java
@Override
public Artifact deserialize(JsonParser parser, DeserializationContext ctxt) 
  throws IOException, JsonProcessingException 
{
    JsonNode node = parser.readValueAsTree();
    ObjectMapper mapper = (ObjectMapper)parser.getCodec();
    ObjectReader reader = null; 
    Object target = null;
    String artifcatType = node.get("artifactType").asText();

    System.out.println(artifcatType);

    if(artifcatType.equalsIgnoreCase("reservedinstance"))
    {
        reader = mapper.readerFor(ReservedInstanceArtifact.class);
    }
    else 
    {
        reader = mapper.readerFor(Artifact.class);
    }

    target = reader.readValue(node);

    return (Artifact)target;
}
 
源代码13 项目: GeoIP2-java   文件: JsonInjector.java
@Override
public Object findInjectableValue(Object valueId, DeserializationContext ctxt,
                                  BeanProperty forProperty, Object beanInstance) {
    if ("locales".equals(valueId)) {
        return locales;
    }
    if ("ip_address".equals(valueId)) {
        return ip;
    }
    if ("network".equals(valueId)) {
        return network;
    }
    if ("traits".equals(valueId)) {
        return new Traits(ip, network);
    }
    return null;
}
 
源代码14 项目: jlineup   文件: CustomDateDeserializer.java
@Override
public Date deserialize(JsonParser paramJsonParser, DeserializationContext paramDeserializationContext)
        throws IOException {
    if (paramJsonParser == null || "".equals(paramJsonParser.getText()))
        return null;
    String date = paramJsonParser.getText();

    for (String format : DATE_FORMATS) {
        try {
            return new SimpleDateFormat(format, Locale.US).parse(date);
        } catch (ParseException e) {
            //This page was left blank intentionally
        }
    }
    throw new IOException("Could not parse date '" + date + "'");
}
 
源代码15 项目: jolt   文件: MappingTest1.java
/**
 * Demonstrates how to do recursive polymorphic JSON deserialization in Jackson 2.2.
 *
 * Aka specify a Deserializer and "catch" some input, determine what type of Class it
 *  should be parsed too, and then reuse the Jackson infrastructure to recursively do so.
 */
@Override
public QueryFilter deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException {

    ObjectNode root = jp.readValueAsTree();

    JsonNode queryParam = root.get("queryParam");
    String value = queryParam.asText();

    // pass in our objectCodec so that the subJsonParser knows about our configured Modules and Annotations
    JsonParser subJsonParser = root.traverse( jp.getCodec() );

    // Determine the "type" of filter we are dealing with Real or Logical and specify type
    if ( "OR".equals( value ) || "AND".equals( value ) ) {
        return subJsonParser.readValueAs( LogicalFilter1.class );
    }
    else {
        return subJsonParser.readValueAs( RealFilter.class );
    }
}
 
@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException {
    final Class<?> classToDeserialize;
    if (property != null) {
        final JavaType type = property.getType();
        classToDeserialize = type.isContainerType() ? type.getContentType().getRawClass() : type.getRawClass();
    } else {
        classToDeserialize = ctxt.getContextualType().getRawClass();
    }

    return new ClassWithInterfaceFieldsDeserializer(classToDeserialize.getName());
}
 
源代码17 项目: streams   文件: GPlusActivityDeserializer.java
/**
 * Because the GooglePlus Activity object {@link com.google.api.services.plus.model.Activity} contains complex objects
 * within its hierarchy, we have to use a custom deserializer
 *
 * @param jsonParser jsonParser
 * @param deserializationContext deserializationContext
 * @return The deserialized {@link com.google.api.services.plus.model.Activity} object
 * @throws IOException IOException
 * @throws JsonProcessingException JsonProcessingException
 */
@Override
public Activity deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {

  JsonNode node = jsonParser.getCodec().readTree(jsonParser);
  Activity activity = new Activity();

  try {
    activity.setUrl(node.get("url").asText());
    activity.setEtag(node.get("etag").asText());
    if( node.has("title") ) {
      activity.setTitle(node.get("title").asText());
    }
    activity.setPublished(DateTime.parseRfc3339(node.get("published").asText()));
    activity.setUpdated(DateTime.parseRfc3339(node.get("updated").asText()));
    activity.setId(node.get("id").asText());
    activity.setVerb(node.get("verb").asText());

    activity.setActor(buildActor(node));

    activity.setObject(buildPlusObject(node));
  } catch (Exception ex) {
    LOGGER.error("Exception while trying to deserialize activity object: {}", ex);
  }

  return activity;
}
 
@Override
public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
	JsonStreamContext jsonStreamContext = p.getParsingContext().getParent();
	InnerSearchHit hit = (InnerSearchHit) jsonStreamContext.getCurrentValue();
	ESClass refs = null;
	if(hit != null) {
		if (hit.getIndex() == null) {
			refs = getESInnerTypeReferences(hit.getType());
		} else {
			refs = getESInnerTypeReferences(getTypeName(p));
		}
	}
	if(refs == null){
		return ctxt.findRootValueDeserializer(ESSerialThreadLocal.getMapObjectType()).deserialize(p,ctxt);
	}
	else
	{
		if(refs instanceof ESTypeReferences)
			return ctxt.findRootValueDeserializer(ESSerialThreadLocal.getJavaType(((ESTypeReferences)refs).getHitType())).deserialize(p,ctxt);
		else
		{
			ESClassType classType = (ESClassType)refs;
			return ctxt.findRootValueDeserializer(ESSerialThreadLocal.getJavaType(classType.getHitClass())).deserialize(p,ctxt);

		}
	}


}
 
源代码19 项目: spring-analysis-note   文件: Jackson2Tokenizer.java
private Jackson2Tokenizer(
		JsonParser parser, DeserializationContext deserializationContext, boolean tokenizeArrayElements) {

	this.parser = parser;
	this.deserializationContext = deserializationContext;
	this.tokenizeArrayElements = tokenizeArrayElements;
	this.tokenBuffer = new TokenBuffer(parser, deserializationContext);
	this.inputFeeder = (ByteArrayFeeder) this.parser.getNonBlockingInputFeeder();
}
 
源代码20 项目: web3j-quorum   文件: OrgDetailsInfo.java
@Override
public OrgDetails deserialize(
        JsonParser jsonParser, DeserializationContext deserializationContext)
        throws IOException {
    if (jsonParser.getCurrentToken() != JsonToken.VALUE_NULL) {
        return om.readValue(jsonParser, OrgDetails.class);
    } else {
        return null;
    }
}
 
@Override
protected YearMonth deserialize(String key, DeserializationContext ctxt) throws IOException {
    try {
        return YearMonth.parse(key, FORMATTER);
    } catch (DateTimeException e) {
        return _handleDateTimeException(ctxt, YearMonth.class, e, key);
    }
}
 
private Object readEncoded(JsonParser p, DeserializationContext ctxt) throws IOException {
    if (!p.isExpectedStartArrayToken()) {
        throw new JsonParseException(p, "Expected array for encoded object got " + p.currentToken());
    }

    Object value = null;
    JsonToken next = p.nextToken();
    if (next != JsonToken.VALUE_STRING) {
        throw new JsonParseException(p, "Encoded Class value not present " + next);
    }
    String typeName = p.getText();
    p.nextToken(); // fwd to next
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    if (loader == null) {
        loader = getClass().getClassLoader();
    }
    try {
        Class<?> type = loader.loadClass(typeName);
        if (Collection.class.isAssignableFrom(type)) {
            value = readCollection(type, p, ctxt);
        } else if (Map.class.isAssignableFrom(type)) {
            value = readMap(type, p, ctxt);
        } else {
            JsonDeserializer<Object> deser = ctxt.findRootValueDeserializer(ctxt.constructType(type));
            value = deser.deserialize(p, ctxt);
        }
    } catch (ClassNotFoundException e) {
        throw new JsonParseException(p, "Type name encoded " + typeName + " could not be loaded", e);
    }
    if (p.nextToken() != JsonToken.END_ARRAY) {
        throw new JsonParseException(p, "Encoded expected end of ARRAY marker " + p.currentToken());
    }
    return value;
}
 
@Override
public HiveProxyingOrcScanFilter deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
  // TODO: Optimize performance as described in https://dremio.atlassian.net/browse/DX-17732
  final JsonNode node = jsonParser.getCodec().readTree(jsonParser);

  final String pluginName = node.get(HiveProxyingOrcScanFilter.JSON_PROP_PLUGINNAME).asText();
  final CatalogService catalogService = (CatalogService) deserializationContext
    .findInjectableValue(CatalogService.class.getName(), null, null);

  final StoragePluginCreator.PF4JStoragePlugin plugin = catalogService.getSource(pluginName);
  final Class<? extends HiveProxiedOrcScanFilter> scanClazz = plugin.getOrcScanFilterClass();

  final JavaType scanType = deserializationContext.getTypeFactory().constructType(scanClazz);
  final BasicBeanDescription description = deserializationContext.getConfig().introspect(scanType);
  final JsonDeserializer<Object> orcScanFilterDeserializer = deserializationContext.getFactory().createBeanDeserializer(
    deserializationContext, scanType, description);

  if (orcScanFilterDeserializer instanceof ResolvableDeserializer) {
    ((ResolvableDeserializer) orcScanFilterDeserializer).resolve(deserializationContext);
  }

  final JsonParser movedParser = jsonParser.getCodec().treeAsTokens(node.get(HiveProxyingOrcScanFilter.JSON_PROP_WRAPPEDHIVEORCSCANFILTER));
  deserializationContext.getConfig().initialize(movedParser);

  if (movedParser.getCurrentToken() == null) {
    movedParser.nextToken();
  }

  final HiveProxiedOrcScanFilter orcScanFilter = (HiveProxiedOrcScanFilter) orcScanFilterDeserializer.deserialize(movedParser, deserializationContext);
  return new HiveProxyingOrcScanFilter(pluginName, orcScanFilter);
}
 
源代码24 项目: weixin-sdk   文件: ReportLocationDeserializer.java
@Override
public WritableAgent.ReportLocation deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
    int report = jsonParser.getIntValue();
    if (1 == report)
        return WritableAgent.ReportLocation.ONLY_IN_SESSION;
    else if (2 == report)
        return WritableAgent.ReportLocation.ALWAYS;
    else
        return WritableAgent.ReportLocation.NO;
}
 
源代码25 项目: webauthn4j   文件: CertPathDeserializer.java
/**
 * {@inheritDoc}
 */
@Override
public CertPath deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {

    ObjectCodec oc = p.getCodec();
    ArrayNode node = oc.readTree(p);
    List<Certificate> list = new ArrayList<>();
    for (JsonNode item : node) {
        X509Certificate certificate = oc.treeToValue(item, X509Certificate.class);
        list.add(certificate);
    }
    return CertificateUtil.generateCertPath(list);
}
 
源代码26 项目: ffwd   文件: TypeFilter.java
@Override
public Filter deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
    final String type = p.nextTextValue();

    if (p.nextToken() != JsonToken.END_ARRAY) {
        throw ctx.wrongTokenException(p, JsonToken.END_ARRAY, null);
    }

    return new TypeFilter(type);
}
 
@Override
public M deserialize(final JsonParser parser, final DeserializationContext context) throws IOException {
    BigDecimal amount = null;
    CurrencyUnit currency = null;

    while (parser.nextToken() != JsonToken.END_OBJECT) {
        final String field = parser.getCurrentName();

        parser.nextToken();

        if (field.equals(names.getAmount())) {
            amount = context.readValue(parser, BigDecimal.class);
        } else if (field.equals(names.getCurrency())) {
            currency = context.readValue(parser, CurrencyUnit.class);
        } else if (field.equals(names.getFormatted())) {
            //noinspection UnnecessaryContinue
            continue;
        } else if (context.isEnabled(FAIL_ON_UNKNOWN_PROPERTIES)) {
            throw UnrecognizedPropertyException.from(parser, MonetaryAmount.class, field,
                    Arrays.asList(names.getAmount(), names.getCurrency(), names.getFormatted()));
        } else {
            parser.skipChildren();
        }
    }

    checkPresent(parser, amount, names.getAmount());
    checkPresent(parser, currency, names.getCurrency());

    return factory.create(amount, currency);
}
 
源代码28 项目: databricks-rest-client   文件: UserDTO.java
@Override
public GroupDTO[] deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
  ObjectCodec oc = p.getCodec();
  ArrayNode node = oc.readTree(p);
  GroupDTO[] groups = new GroupDTO[node.size()];
  for (int i = 0; i < node.size(); i++) {
    JsonNode current = node.get(i);
    groups[i] = new GroupDTO();
    groups[i].setId(Long.parseLong(current.get("value").asText()));
    groups[i].setDisplay(current.get("display").asText());
  }
  return groups;
}
 
源代码29 项目: powsybl-core   文件: BarExtSerializer.java
@Override
public BarExt deserializeAndUpdate(JsonParser jsonParser, DeserializationContext deserializationContext, BarExt parameters) throws IOException {
    ObjectMapper objectMapper = createMapper();
    ObjectReader objectReader = objectMapper.readerForUpdating(parameters);
    BarExt updatedParameters = objectReader.readValue(jsonParser, BarExt.class);
    return updatedParameters;
}
 
源代码30 项目: alchemy   文件: ClassKeyDeserializer.java
@Override
public Object deserializeKey(String className, DeserializationContext context) throws IOException {
    try {
        return Class.forName(className);
    } catch (ClassNotFoundException e) {
        throw new IOException(String.format("could not find class %s", className));
    }
}
 
如果文章对您有帮助,请点击页面广告。以鼓励作者做出的努力。
 同包方法