com.fasterxml.jackson.databind.DeserializationContext Java Examples

The following examples show how to use com.fasterxml.jackson.databind.DeserializationContext. 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: AbstractDeviceRenderTypeMapDeserializer.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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;
}
 
Example #2
Source File: JSonBindingUtils.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #3
Source File: CustomCollectionDeserializer.java    From caravan with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #4
Source File: MiscTest.java    From td-ameritrade-client with Apache License 2.0 6 votes vote down vote up
@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");
  }
}
 
Example #5
Source File: ColumnPartitionMetadata.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #6
Source File: JavaUtilCollectionsDeserializers.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
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);
}
 
Example #7
Source File: ContextDataDeserializer.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@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;
    }
 
Example #8
Source File: GetTableLayoutRequestSerDe.java    From aws-athena-query-federation with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #9
Source File: FlexDateDeserializer.java    From shopify-api-java-wrapper with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #10
Source File: ArtifactDeserializer.java    From Partner-Center-Java with MIT License 6 votes vote down vote up
@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;
}
 
Example #11
Source File: JsonInjector.java    From GeoIP2-java with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #12
Source File: NodeDeserializer.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #13
Source File: CustomDateDeserializer.java    From jlineup with Apache License 2.0 6 votes vote down vote up
@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 + "'");
}
 
Example #14
Source File: MappingTest1.java    From jolt with Apache License 2.0 6 votes vote down vote up
/**
 * 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 );
    }
}
 
Example #15
Source File: SourceForgeSearchResultDeserialiser.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
@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;
}
 
Example #16
Source File: ClientCsdlComplexType.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
protected CsdlComplexType doDeserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException {

  final ClientCsdlComplexType complexType = new ClientCsdlComplexType();

  for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
    final JsonToken token = jp.getCurrentToken();
    if (token == JsonToken.FIELD_NAME) {
      if ("Name".equals(jp.getCurrentName())) {
        complexType.setName(jp.nextTextValue());
      } else if ("Abstract".equals(jp.getCurrentName())) {
        complexType.setAbstract(BooleanUtils.toBoolean(jp.nextTextValue()));
      } else if ("BaseType".equals(jp.getCurrentName())) {
        complexType.setBaseType(jp.nextTextValue());
      } else if ("OpenType".equals(jp.getCurrentName())) {
        complexType.setOpenType(BooleanUtils.toBoolean(jp.nextTextValue()));
      } else if ("Property".equals(jp.getCurrentName())) {
        jp.nextToken();
        complexType.getProperties().add(jp.readValueAs(ClientCsdlProperty.class));
      } else if ("NavigationProperty".equals(jp.getCurrentName())) {
        jp.nextToken();
        complexType.getNavigationProperties().add(jp.readValueAs(ClientCsdlNavigationProperty.class));
      } else if ("Annotation".equals(jp.getCurrentName())) {
        jp.nextToken();
        complexType.getAnnotations().add(jp.readValueAs(ClientCsdlAnnotation.class));
      }
    }
  }

  return complexType;
}
 
Example #17
Source File: ClassKeyDeserializer.java    From alchemy with MIT License 5 votes vote down vote up
@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));
    }
}
 
Example #18
Source File: LandscaperDeserializer.java    From ure with MIT License 5 votes vote down vote up
@Override
public ULandscaper deserialize(JsonParser parser, DeserializationContext context) throws IOException {
    ObjectCodec codec = parser.getCodec();
    JsonNode node = codec.readTree(parser);
    JsonNode typeNode = node.get("type");
    String type = (typeNode != null && !typeNode.isNull()) ? node.get("type").asText() : null;
    Class<? extends ULandscaper> landscaperClass = classForType(type);
    return objectMapper.treeToValue(node, landscaperClass);
}
 
Example #19
Source File: MapDeserializer.java    From caravan with Apache License 2.0 5 votes vote down vote up
public MapDeserializer(JavaType pairType) {
  super(
      CollectionType.construct(ArrayList.class, null, null, null, pairType), //
      null, null, new ValueInstantiator() {
        @Override
        public Object createUsingDefault(DeserializationContext ctxt) throws IOException {
          return new ArrayList();
        }
      });
}
 
Example #20
Source File: ChallengeDeserializer.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Challenge deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    String str = p.getValueAsString();
    try {
        return new DefaultChallenge(str);
    } catch (IllegalArgumentException e) {
        throw new InvalidFormatException(null, "value is out of range", str, DefaultChallenge.class);
    }
}
 
Example #21
Source File: CustomDateDeserializer.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public Date deserialize(JsonParser jsonparser, DeserializationContext context)
        throws IOException, JsonProcessingException {
    String date = jsonparser.getText();
    try {
        return formatter.parse(date);
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }
}
 
Example #22
Source File: DeserializerTest.java    From nodes with Apache License 2.0 5 votes vote down vote up
@Test
public void deserializeSimple() throws IOException {
    String json = (
        "{\n" +
        "  \"test\": {\n" +
        "    \"testString\": \"String\",\n" +
        "    \"testByte\": \"1\",\n" +
        "    \"testShort\": \"1\",\n" +
        "    \"testInteger\": 1,\n" +
        "    \"testLong\": 1,\n" +
        "    \"testCharacter\": \"a\",\n" +
        "    \"testFloat\": 1.5,\n" +
        "    \"testDouble\": 1.5,\n" +
        "    \"testBoolean\": true,\n" +
        "    \"nestedTest\": {\n" +
        "      \"anotherTestString\": \"AnotherString\"\n" +
        "    },\n" +
        "    \"testArrayList\": [\n" +
        "      \"val1\",\n" +
        "      \"val2\"\n" +
        "    ],\n" +
        "    \"testList\": [\n" +
        "      {\n" +
        "        \"anotherTestString\": \"AnotherString\"\n" +
        "      }\n" +
        "    ]\n" +
        "  }\n" +
        "}"
    );
    InputStream stream = new ByteArrayInputStream(json.getBytes());
    JsonParser parser = mapper.getFactory().createParser(stream);
    DeserializationContext ctxt = mapper.getDeserializationContext();
    Deserializer<TestModel> deserializer = new Deserializer<TestModel>(TestModel.class, objectMapperFactory);
    Resource<TestModel> res = deserializer.deserialize(parser, ctxt);
    assertEquals("Resource{resource=TestTO{testString='String', testByte=1, testShort=1, testInteger=1, testLong=1, testCharacter=a, testFloat=1.5, testDouble=1.5, testBoolean=true, nestedTest=NestedTest{anotherTestString='AnotherString', andAnothaOne='null'}, testArrayList=[val1, val2], testList=[NestedTest{anotherTestString='AnotherString', andAnothaOne='null'}], ignoredField='null'}}", res.toString());
}
 
Example #23
Source File: ClassWithInterfaceFieldsDeserializer.java    From istio-java-api with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #24
Source File: BaseCollectionDeserializer.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public T deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException {
    // Should usually point to START_ARRAY
    if (p.isExpectedStartArrayToken()) {
        return _deserializeContents(p, ctxt);
    }
    // But may support implicit arrays from single values?
    if (ctxt.isEnabled(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)) {
        return _deserializeFromSingleValue(p, ctxt);
    }
    return (T) ctxt.handleUnexpectedToken(getValueType(ctxt), p);
}
 
Example #25
Source File: ItemDeserializer.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * {"id":1,"itemNr":"theItem","owner":2}
 */
@Override
public Item deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
    final JsonNode node = jp.getCodec()
        .readTree(jp);
    final int id = (Integer) ((IntNode) node.get("id")).numberValue();
    final String itemName = node.get("itemName")
        .asText();
    final int userId = (Integer) ((IntNode) node.get("createdBy")).numberValue();

    return new Item(id, itemName, new User(userId, null));
}
 
Example #26
Source File: TestSupport.java    From jackson-lombok with MIT License 5 votes vote down vote up
@Override
public Integer deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    String value = jp.getText();
    try {
        return Integer.valueOf(value) + 1;

    } catch (NumberFormatException e) {
        return -1;
    }
}
 
Example #27
Source File: LocalDateTimeDeserializer.java    From bootique with Apache License 2.0 5 votes vote down vote up
@Override
public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException {
    if (parser.hasTokenId(JsonTokenId.ID_STRING)) {
        String string = parser.getText().trim();
        if (string.length() == 0) {
            return null;
        }
        return LocalDateTime.parse(string, _formatter);
    }

    throw context.wrongTokenException(parser, JsonToken.START_ARRAY, "Expected array or string.");
}
 
Example #28
Source File: ServletRequestParamReader.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Override
public SimpleDate deserialize(JsonParser jsonParser, DeserializationContext context)
    throws IOException {
  String value = jsonParser.readValueAs(String.class).trim();
  Matcher matcher = pattern.matcher(value);
  if (matcher.find()) {
    int year = Integer.parseInt(matcher.group(1));
    int month = Integer.parseInt(matcher.group(2));
    int day = Integer.parseInt(matcher.group(3));
    return new SimpleDate(year, month, day);
  } else {
    throw new IllegalArgumentException(
        "String is not an RFC3339 formated date (yyyy-mm-dd): " + value);
  }
}
 
Example #29
Source File: JacksonDeserializer.java    From jjwt with Apache License 2.0 5 votes vote down vote up
@Override
public Object deserialize(JsonParser parser, DeserializationContext context) throws IOException {
    // check if the current claim key is mapped, if so traverse it's value
    String name = parser.currentName();
    if (claimTypeMap != null && name != null && claimTypeMap.containsKey(name)) {
        Class type = claimTypeMap.get(name);
        return parser.readValueAsTree().traverse(parser.getCodec()).readValueAs(type);
    }
    // otherwise default to super
    return super.deserialize(parser, context);
}
 
Example #30
Source File: MultiDateDeserializer.java    From nimble-orm with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
	JsonNode node = jp.getCodec().readTree(jp);

	// 针对时间戳做优化
	if(node instanceof LongNode || node instanceof IntNode) {
		long timestamp = node.asLong();
		if(timestamp < 4200000000L) { // 小于42亿认为是秒
			return new Date(timestamp * 1000L);
		} else {
			return new Date(timestamp);
		}
	}

	String date = node.asText();
	if(date == null) {
		return null;
	}
	date = date.trim();
	if(date.isEmpty()) {
		return null;
	}
	
	try {
		return NimbleOrmDateUtils.parseThrowException(date);
	} catch (ParseException e) {
		throw new JsonParseException(jp,
		    "Unparseable date: \"" + date + "\". Supported formats: " 
		    + NimbleOrmDateUtils.DATE_FORMAT_REGEXPS.values());
	}
}