com.fasterxml.jackson.core.JsonParser Java Examples

The following examples show how to use com.fasterxml.jackson.core.JsonParser. 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: SnapshotParser.java    From synapse with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> void processSnapshotData(final JsonParser parser,
                                     final ChannelPosition channelPosition,
                                     final MessageDispatcher messageDispatcher) throws IOException {
    final Decoder<SnapshotMessage> decoder = new SnapshotMessageDecoder();
    final ShardPosition shardPosition = channelPosition.shard(channelPosition.shards().iterator().next());
    while (parser.nextToken() != JsonToken.END_ARRAY) {
        JsonToken currentToken = parser.currentToken();
        if (currentToken == JsonToken.FIELD_NAME) {
            final TextMessage message = decoder.apply(new SnapshotMessage(
                    Key.of(parser.getValueAsString()),
                    Header.of(shardPosition),
                    parser.nextTextValue()));
            messageDispatcher.accept(message);
        }
    }
}
 
Example #2
Source File: PropertiesBuilder.java    From querqy with Apache License 2.0 6 votes vote down vote up
public PropertiesBuilder() {
    objectMapper = new ObjectMapper();
    objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    objectMapper.configure(JsonParser.Feature.ALLOW_YAML_COMMENTS, true);
    objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
    objectMapper.configure(JsonParser.Feature.ALLOW_NUMERIC_LEADING_ZEROS, true);
    objectMapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true);



    jsonPathConfiguration = Configuration.builder()
            .jsonProvider(new JacksonJsonProvider())
            .mappingProvider(new JacksonMappingProvider()).build();
    jsonPathConfiguration.addOptions(Option.ALWAYS_RETURN_LIST);

    primitiveProperties = new HashMap<>();
    jsonObjectString =  new StringBuilder();

}
 
Example #3
Source File: CloudErrorDeserializer.java    From autorest-clientruntime-for-java with MIT License 6 votes vote down vote up
@Override
public CloudError deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    p.setCodec(mapper);
    JsonNode errorNode = p.readValueAsTree();

    if (errorNode == null) {
        return null;
    }
    if (errorNode.get("error") != null) {
        errorNode = errorNode.get("error");
    }
    
    JsonParser parser = new JsonFactory().createParser(errorNode.toString());
    parser.setCodec(mapper);
    return parser.readValueAs(CloudError.class);
}
 
Example #4
Source File: ClassWithInterfaceFieldsRegistry.java    From istio-java-api with Apache License 2.0 6 votes vote down vote up
Object deserialize(JsonNode node, String fieldName, Class targetClass, DeserializationContext ctxt) throws IOException {
    final String type = getFieldClassFQN(targetClass, valueType);
    try {
        // load class of the field
        final Class<?> fieldClass = Thread.currentThread().getContextClassLoader().loadClass(type);
        // create a map type matching the type of the field from the mapping information
        final YAMLMapper codec = (YAMLMapper) ctxt.getParser().getCodec();
        MapType mapType = codec.getTypeFactory().constructMapType(Map.class, String.class, fieldClass);
        // get a parser taking the current value as root
        final JsonParser traverse = node.get(fieldName).traverse(codec);
        // and use it to deserialize the subtree as the map type we just created
        return codec.readValue(traverse, mapType);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("Unsupported type '" + type + "' for field '" + fieldName +
                "' on '" + targetClass.getName() + "' class. Full type was " + this, e);
    }
}
 
Example #5
Source File: JsonJacksonFormat.java    From jigsaw-payment with Apache License 2.0 6 votes vote down vote up
private void handleValue(JsonParser parser,
                                ExtensionRegistry extensionRegistry,
                                Message.Builder builder,
                                FieldDescriptor field,
                                ExtensionRegistry.ExtensionInfo extension,
                                boolean unknown) throws IOException {

    Object value = null;
    if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
        value = handleObject(parser, extensionRegistry, builder, field, extension, unknown);
    } else {
        value = handlePrimitive(parser, field);
    }
    if (value != null) {
        if (field.isRepeated()) {
            builder.addRepeatedField(field, value);
        } else {
            builder.setField(field, value);
        }
    }
}
 
Example #6
Source File: FeaturesExtractorManager.java    From ltr4l with Apache License 2.0 6 votes vote down vote up
public SimpleOrderedMap<Object> getResult(){
  if(future.isDone()){
    SimpleOrderedMap<Object> result = new SimpleOrderedMap<Object>();
    Reader r = null;
    try{
      r = new FileReader(featuresFile);
      ObjectMapper mapper = new ObjectMapper();
      mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
      Map<String, Object> json = mapper.readValue(featuresFile, Map.class);
      result.add("data", parseData(json));
      return result;
    } catch (IOException e) {
      throw new RuntimeException(e);
    } finally{
      IOUtils.closeWhileHandlingException(r);
    }
  }
  else return null;
}
 
Example #7
Source File: ClientCsdlReference.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
protected ClientCsdlReference doDeserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException {
  final ClientCsdlReference reference = new ClientCsdlReference();

  for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
    final JsonToken token = jp.getCurrentToken();
    if (token == JsonToken.FIELD_NAME) {
      if ("Uri".equals(jp.getCurrentName())) {
        reference.setUri(URI.create(jp.nextTextValue()));
      } else if ("Include".equals(jp.getCurrentName())) {
        jp.nextToken();
        reference.getIncludes().add(jp.readValueAs( ClientCsdlInclude.class));
      } else if ("IncludeAnnotations".equals(jp.getCurrentName())) {
        jp.nextToken();
        reference.getIncludeAnnotations().add(jp.readValueAs( ClientCsdlIncludeAnnotations.class));
      } else if ("Annotation".equals(jp.getCurrentName())) {
        jp.nextToken();
        reference.getAnnotations().add(jp.readValueAs( ClientCsdlAnnotation.class));
      }
    }
  }

  return reference;
}
 
Example #8
Source File: JsonProcessor.java    From odata with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize processor, automatically scanning the input JSON.
 * @throws ODataUnmarshallingException If unable to initialize
 */
public void initialize() throws ODataUnmarshallingException {
    LOG.info("Parser is initializing");
    try {
        JsonParser jsonParser = JSON_FACTORY.createParser(inputJson);

        while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
            String token = jsonParser.getCurrentName();
            if (token != null) {
                if (token.startsWith(ODATA)) {
                    processSpecialTags(jsonParser);
                } else if (token.endsWith(ODATA_BIND)) {
                    processLinks(jsonParser);
                } else {
                    process(jsonParser);
                }
            }
        }
    } catch (IOException e) {
        throw new ODataUnmarshallingException("It is unable to unmarshall", e);
    }
}
 
Example #9
Source File: HeaderMapDeserializer.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * @see com.fasterxml.jackson.databind.JsonDeserializer#deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext)
 */
@Override
public HeaderMap deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    HeaderMap map = new HeaderMap();

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

        p.nextToken();

        if (p.currentToken().isScalarValue()) {
            map.add(name, p.getValueAsString());
        } else {
            ArrayDeque<String> values = new ArrayDeque<>();
            while (p.nextToken() != JsonToken.END_ARRAY) {
                values.push(p.getValueAsString());
            }
            values.forEach(value -> map.add(name, value));
        }
    }
    return map;
}
 
Example #10
Source File: JsonPreKeyStore.java    From signal-cli with GNU General Public License v3.0 6 votes vote down vote up
@Override
public JsonPreKeyStore deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
    JsonNode node = jsonParser.getCodec().readTree(jsonParser);

    Map<Integer, byte[]> preKeyMap = new HashMap<>();
    if (node.isArray()) {
        for (JsonNode preKey : node) {
            Integer preKeyId = preKey.get("id").asInt();
            try {
                preKeyMap.put(preKeyId, Base64.decode(preKey.get("record").asText()));
            } catch (IOException e) {
                System.out.println(String.format("Error while decoding prekey for: %s", preKeyId));
            }
        }
    }

    JsonPreKeyStore keyStore = new JsonPreKeyStore();
    keyStore.addPreKeys(preKeyMap);

    return keyStore;

}
 
Example #11
Source File: CloudErrorDeserializer.java    From botbuilder-java with MIT License 6 votes vote down vote up
@Override
public CloudError deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    p.setCodec(mapper);
    JsonNode errorNode = p.readValueAsTree();

    if (errorNode == null) {
        return null;
    }
    if (errorNode.get("error") != null) {
        errorNode = errorNode.get("error");
    }

    JsonParser parser = new JsonFactory().createParser(errorNode.toString());
    parser.setCodec(mapper);
    return parser.readValueAs(CloudError.class);
}
 
Example #12
Source File: PropertyExtractingEventReader.java    From fahrschein with Apache License 2.0 6 votes vote down vote up
@Override
public List<T> read(JsonParser jsonParser) throws IOException {
    expectToken(jsonParser.nextToken(), JsonToken.START_ARRAY);

    final List<T> result = new ArrayList<>();

    for (JsonToken token = jsonParser.nextToken(); token != JsonToken.END_ARRAY; token = jsonParser.nextToken()) {
        expectToken(token, JsonToken.START_OBJECT);

        for (token = jsonParser.nextToken(); token != JsonToken.END_OBJECT; token = jsonParser.nextToken()) {
            expectToken(token, JsonToken.FIELD_NAME);

            final String topLevelProperty = jsonParser.getCurrentName();
            jsonParser.nextToken();

            if (propertyName.equals(topLevelProperty)) {
                final T value = getValue(jsonParser);
                result.add(value);
            } else {
                jsonParser.skipChildren();
            }
        }
    }

    return result;
}
 
Example #13
Source File: PermissionNodeList.java    From web3j-quorum with Apache License 2.0 6 votes vote down vote up
@Override
public List<PermissionNodeInfo> deserialize(
        JsonParser jsonParser, DeserializationContext deserializationContext)
        throws IOException {
    List<PermissionNodeInfo> nodeList = new ArrayList<>();
    JsonToken nextToken = jsonParser.nextToken();

    if (nextToken == JsonToken.START_OBJECT) {
        Iterator<PermissionNodeInfo> nodeInfoIterator =
                om.readValues(jsonParser, PermissionNodeInfo.class);
        while (nodeInfoIterator.hasNext()) {
            nodeList.add(nodeInfoIterator.next());
        }
        return nodeList;
    } else {
        return null;
    }
}
 
Example #14
Source File: AvroGenericRecordMapper.java    From divolte-collector with Apache License 2.0 6 votes vote down vote up
private List<?> readArray(final JsonParser parser,
                          final Schema targetSchema) throws IOException {
    Preconditions.checkArgument(targetSchema.getType() == Schema.Type.ARRAY);
    final List<?> result;
    final Schema elementType = targetSchema.getElementType();
    if (parser.isExpectedStartArrayToken()) {
        final List<Object> builder = new ArrayList<>();
        while (JsonToken.END_ARRAY != parser.nextToken()) {
            builder.add(read(parser, elementType));
        }
        result = builder;
    } else if (reader.isEnabled(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)) {
        result = Collections.singletonList(read(parser, elementType));
    } else {
        throw mappingException(parser, targetSchema);
    }
    return result;
}
 
Example #15
Source File: NativeRequestExtReader.java    From openrtb-doubleclick with Apache License 2.0 6 votes vote down vote up
@Override protected void read(NativeRequestExt.Builder ext, JsonParser par) throws IOException {
  switch (getCurrentName(par)) {
    case "style_id":
      ext.setStyleId(par.nextIntValue(0));
      break;
    case "style_height":
      ext.setStyleHeight(par.nextIntValue(0));
      break;
    case "style_width":
      ext.setStyleWidth(par.nextIntValue(0));
      break;
    case "style_layout_type": {
        LayoutType value = LayoutType.forNumber(par.nextIntValue(0));
        if (checkEnum(value)) {
          ext.setStyleLayoutType(value);
        }
      }
      break;
  }
}
 
Example #16
Source File: BidExtReader.java    From openrtb-doubleclick with Apache License 2.0 5 votes vote down vote up
protected void readEventNotificationTokenField(
    JsonParser par, EventNotificationToken.Builder token, String fieldName)
        throws IOException {
  switch (fieldName) {
    case "payload":
      token.setPayload(par.getText());
      break;
  }
}
 
Example #17
Source File: ParseSupport.java    From curiostack with MIT License 5 votes vote down vote up
/** Parsers a bool value out of the input. */
public static boolean parseBool(JsonParser parser) throws IOException {
  JsonToken token = parser.currentToken();
  if (token.isBoolean()) {
    return parser.getBooleanValue();
  }
  String json = parser.getText();
  if (json.equals("true")) {
    return true;
  } else if (json.equals("false")) {
    return false;
  }
  throw new InvalidProtocolBufferException("Invalid bool value: " + json);
}
 
Example #18
Source File: DbxClientV1.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Override
public ChunkedUploadState read(JsonParser parser) throws IOException, JsonReadException
{
    JsonLocation top = JsonReader.expectObjectStart(parser);

    String uploadId = null;
    long bytesComplete = -1;

    while (parser.getCurrentToken() == JsonToken.FIELD_NAME) {
        String fieldName = parser.getCurrentName();
        parser.nextToken();

        try {
            if (fieldName.equals("upload_id")) {
                uploadId = JsonReader.StringReader.readField(parser, fieldName, uploadId);
            }
            else if (fieldName.equals("offset")) {
                bytesComplete = JsonReader.readUnsignedLongField(parser, fieldName, bytesComplete);
            }
            else {
                JsonReader.skipValue(parser);
            }
        }
        catch (JsonReadException ex) {
            throw ex.addFieldContext(fieldName);
        }
    }

    JsonReader.expectObjectEnd(parser);

    if (uploadId == null) throw new JsonReadException("missing field \"upload_id\"", top);
    if (bytesComplete == -1) throw new JsonReadException("missing field \"offset\"", top);

    return new ChunkedUploadState(uploadId, bytesComplete);
}
 
Example #19
Source File: StreamsJacksonMapper.java    From streams with Apache License 2.0 5 votes vote down vote up
public void configure() {
  disable(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
  configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE);
  configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, Boolean.TRUE);
  configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, Boolean.TRUE);
  configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, Boolean.TRUE);
  configure(DeserializationFeature.WRAP_EXCEPTIONS, Boolean.FALSE);
  configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, Boolean.TRUE);
  // If a user has an 'object' that does not have an explicit mapping, don't cause the serialization to fail.
  configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, Boolean.FALSE);
  configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, Boolean.FALSE);
  configure(SerializationFeature.WRITE_NULL_MAP_VALUES, Boolean.FALSE);
  setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.DEFAULT);
  setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
}
 
Example #20
Source File: LongBeanTable.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * for attribute value parsing
 */
public static long[] parseValue(byte[] input) {
  if (input==null) {
    return null;
  }
  KriptonJsonContext context=KriptonBinder.jsonBind();
  try (JacksonWrapperParser wrapper=context.createParser(input)) {
    JsonParser jacksonParser=wrapper.jacksonParser;
    // START_OBJECT
    jacksonParser.nextToken();
    // value of "element"
    jacksonParser.nextValue();
    long[] result=null;
    if (jacksonParser.currentToken()==JsonToken.START_ARRAY) {
      ArrayList<Long> collection=new ArrayList<>();
      Long item=null;
      while (jacksonParser.nextToken() != JsonToken.END_ARRAY) {
        if (jacksonParser.currentToken()==JsonToken.VALUE_NULL) {
          item=null;
        } else {
          item=jacksonParser.getLongValue();
        }
        collection.add(item);
      }
      result=CollectionUtils.asLongTypeArray(collection);
    }
    return result;
  } catch(Exception e) {
    e.printStackTrace();
    throw(new KriptonRuntimeException(e.getMessage()));
  }
}
 
Example #21
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 #22
Source File: Bean64Table.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * for attribute valueLongList parsing
 */
public static LinkedList<Long> parseValueLongList(byte[] input) {
  if (input==null) {
    return null;
  }
  KriptonJsonContext context=KriptonBinder.jsonBind();
  try (JacksonWrapperParser wrapper=context.createParser(input)) {
    JsonParser jacksonParser=wrapper.jacksonParser;
    // START_OBJECT
    jacksonParser.nextToken();
    // value of "element"
    jacksonParser.nextValue();
    LinkedList<Long> result=null;
    if (jacksonParser.currentToken()==JsonToken.START_ARRAY) {
      LinkedList<Long> collection=new LinkedList<>();
      Long item=null;
      while (jacksonParser.nextToken() != JsonToken.END_ARRAY) {
        if (jacksonParser.currentToken()==JsonToken.VALUE_NULL) {
          item=null;
        } else {
          item=jacksonParser.getLongValue();
        }
        collection.add(item);
      }
      result=collection;
    }
    return result;
  } catch(Exception e) {
    e.printStackTrace();
    throw(new KriptonRuntimeException(e.getMessage()));
  }
}
 
Example #23
Source File: StringToListDerializer.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public Object deserializeWithType(JsonParser p, DeserializationContext ctxt, TypeDeserializer typeDeserializer) throws IOException {
//    	Object obj = ctxt.des
//    	return typeDeserializer.deserializeTypedFromArray(p, ctxt);
    	Object val = deserialize(p, ctxt);
//    	typeDeserializer.de
//    	Object val = super.deserializeWithType(p, ctxt, typeDeserializer);
    	return val;
    }
 
Example #24
Source File: JacksonParser.java    From JsonSurfer with MIT License 5 votes vote down vote up
JacksonResumableParser(final JsonParser jsonParser, SurfingContext context) {
    this.jsonParser = jsonParser;
    this.context = context;
    final JsonProvider jsonProvider = context.getConfig().getJsonProvider();
    this.stringHolder = new AbstractPrimitiveHolder(context.getConfig()) {
        @Override
        public Object doGetValue() throws IOException {
            return jsonProvider.primitive(jsonParser.getText());
        }

        @Override
        public void doSkipValue() throws IOException {
        }
    };
    this.longHolder = new AbstractPrimitiveHolder(context.getConfig()) {
        @Override
        public Object doGetValue() throws IOException {
            return jsonProvider.primitive(jsonParser.getLongValue());
        }

        @Override
        public void doSkipValue() throws IOException {
        }
    };
    this.doubleHolder = new AbstractPrimitiveHolder(context.getConfig()) {
        @Override
        public Object doGetValue() throws IOException {
            return jsonProvider.primitive(jsonParser.getDoubleValue());
        }

        @Override
        public void doSkipValue() throws IOException {
        }
    };
    this.staticHolder = new StaticPrimitiveHolder();
}
 
Example #25
Source File: CapturingCodec.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Iterator<T> readValues(final JsonParser p, final TypeReference<T> valueTypeRef) throws IOException {
    final Iterator<T> ret = delegate.readValues(p, valueTypeRef);
    captured = ret;

    return ret;
}
 
Example #26
Source File: IntegerDaoImpl.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * for param parser1 parsing
 */
private List<Integer> parser1(byte[] input) {
  if (input==null) {
    return null;
  }
  KriptonJsonContext context=KriptonBinder.jsonBind();
  try (JacksonWrapperParser wrapper=context.createParser(input)) {
    JsonParser jacksonParser=wrapper.jacksonParser;
    // START_OBJECT
    jacksonParser.nextToken();
    // value of "element"
    jacksonParser.nextValue();
    List<Integer> result=null;
    if (jacksonParser.currentToken()==JsonToken.START_ARRAY) {
      ArrayList<Integer> collection=new ArrayList<>();
      Integer item=null;
      while (jacksonParser.nextToken() != JsonToken.END_ARRAY) {
        if (jacksonParser.currentToken()==JsonToken.VALUE_NULL) {
          item=null;
        } else {
          item=jacksonParser.getIntValue();
        }
        collection.add(item);
      }
      result=collection;
    }
    return result;
  } catch(Exception e) {
    e.printStackTrace();
    throw(new KriptonRuntimeException(e.getMessage()));
  }
}
 
Example #27
Source File: BeanTable.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * for attribute valueShortSet parsing
 */
public static HashSet<Short> parseValueShortSet(byte[] input) {
  if (input==null) {
    return null;
  }
  KriptonJsonContext context=KriptonBinder.jsonBind();
  try (JacksonWrapperParser wrapper=context.createParser(input)) {
    JsonParser jacksonParser=wrapper.jacksonParser;
    // START_OBJECT
    jacksonParser.nextToken();
    // value of "element"
    jacksonParser.nextValue();
    HashSet<Short> result=null;
    if (jacksonParser.currentToken()==JsonToken.START_ARRAY) {
      HashSet<Short> collection=new HashSet<>();
      Short item=null;
      while (jacksonParser.nextToken() != JsonToken.END_ARRAY) {
        if (jacksonParser.currentToken()==JsonToken.VALUE_NULL) {
          item=null;
        } else {
          item=jacksonParser.getShortValue();
        }
        collection.add(item);
      }
      result=collection;
    }
    return result;
  } catch(Exception e) {
    e.printStackTrace();
    throw(new KriptonRuntimeException(e.getMessage()));
  }
}
 
Example #28
Source File: BindMapHelper.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * Parse a map.
 *
 * @param context the context
 * @param parserWrapper the parser wrapper
 * @param map the map
 * @return map
 */
public static Map<String, Object> parseMap(AbstractContext context, ParserWrapper parserWrapper, Map<String, Object> map) {
	switch (context.getSupportedFormat()) {
	case XML:
		throw (new KriptonRuntimeException(context.getSupportedFormat() + " context does not support parse direct map parsing"));
	default:
		JacksonWrapperParser wrapperParser = (JacksonWrapperParser) parserWrapper;
		JsonParser parser = wrapperParser.jacksonParser;

		map.clear();
		return parseMap(context, parser, map, false);
	}
}
 
Example #29
Source File: EntityParser.java    From components with Apache License 2.0 5 votes vote down vote up
/**
 * Rewinds {@link JsonParser} to the value of specified field
 * 
 * @param parser JSON parser
 * @param fieldName name of field rewind to
 * @return true if field was found, false otherwise
 * @throws IOException in case of exception during JSON parsing
 */
private static boolean rewindToField(JsonParser parser, final String fieldName) throws IOException {

    JsonToken currentToken = parser.nextToken();
    /*
     * There is no special token, which denotes end of file, in Jackson.
     * This counter is used to define the end of file.
     * The counter counts '{' and '}'. It is increased, when meets '{' and
     * decreased, when meets '}'. When braceCounter == 0 it means the end
     * of file was met
     */
    int braceCounter = 0;
    String currentField = null;
    do {
        if (JsonToken.START_OBJECT == currentToken) {
            braceCounter++;
        }
        if (JsonToken.END_OBJECT == currentToken) {
            braceCounter--;
        }
        if (JsonToken.FIELD_NAME == currentToken) {
            currentField = parser.getCurrentName();
        }
        currentToken = parser.nextToken();
    } while (!fieldName.equals(currentField) && braceCounter != END_JSON);

    return braceCounter != END_JSON;
}
 
Example #30
Source File: KubernetesDeserializer.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public KubernetesResource deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonNode node = jp.readValueAsTree();
    if (node.isObject()) {
        return fromObjectNode(jp, node);
    } else if (node.isArray()) {
        return fromArrayNode(jp, node);
    } else {
        return null;
    }
}