Java Code Examples for com.fasterxml.jackson.core.JsonParser#getIntValue()

The following examples show how to use com.fasterxml.jackson.core.JsonParser#getIntValue() . 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: TestJsonParser.java    From geometry-api-java with Apache License 2.0 6 votes vote down vote up
@Test
public static int fromJsonToWkid(JsonParser parser) throws JsonParseException, IOException {
	int wkid = 0;
	if (parser.getCurrentToken() != JsonToken.START_OBJECT) {
		return 0;
	}

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

		if ("wkid".equals(fieldName)) {
			parser.nextToken();
			wkid = parser.getIntValue();
		}
	}
	return wkid;
}
 
Example 2
Source File: EnumCustomizationFactory.java    From caravan with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public JsonDeserializer createDeserializer() {
  return new StdDeserializer<Enum>(Enum.class) {
    @Override
    public Enum deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
      CustomProtobufParser pp = (CustomProtobufParser) p;

      Class<Enum> enumType = ProtobufParserUtil.getEnumClassOfCurrentField(pp.getCurrentMessage(), pp.getCurrentField());

      switch (protobufConfig.getEnumMode()) {
        case ByOrdinal:
          // minus 1 to match .net
          int ordinal = p.getIntValue() - 1;
          return enumType.getEnumConstants()[ordinal];
        case ByValue:
          return createEnumFromValue(enumType, p.getIntValue());
      }

      throw new RuntimeException("unknown enum mode " + protobufConfig.getEnumMode());
    }
  };
}
 
Example 3
Source File: MockKeyFrameBindMap.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * parse with jackson
 */
@Override
public MockKeyFrame parseOnJackson(JsonParser jacksonParser) throws Exception {
  MockKeyFrame instance = new MockKeyFrame();
  String fieldName;
  if (jacksonParser.currentToken() == null) {
    jacksonParser.nextToken();
  }
  if (jacksonParser.currentToken() != JsonToken.START_OBJECT) {
    jacksonParser.skipChildren();
    return instance;
  }
  while (jacksonParser.nextToken() != JsonToken.END_OBJECT) {
    fieldName = jacksonParser.getCurrentName();
    jacksonParser.nextToken();

    // Parse fields:
    switch (fieldName) {
        case "name":
          // field name (mapped with "name")
          if (jacksonParser.currentToken()!=JsonToken.VALUE_NULL) {
            instance.name=jacksonParser.getText();
          }
        break;
        case "duration":
          // field duration (mapped with "duration")
          instance.duration=jacksonParser.getLongValue();
        break;
        case "val":
          // field val (mapped with "val")
          instance.val=jacksonParser.getIntValue();
        break;
        default:
          jacksonParser.skipChildren();
        break;}
  }
  return instance;
}
 
Example 4
Source File: ReportLocationDeserializer.java    From weixin-sdk with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 5
Source File: IntDaoImpl.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * for param parser1 parsing
 */
private int[] 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();
    int[] 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=CollectionUtils.asIntegerTypeArray(collection);
    }
    return result;
  } catch(Exception e) {
    e.printStackTrace();
    throw(new KriptonRuntimeException(e.getMessage()));
  }
}
 
Example 6
Source File: MassChargeCalculator.java    From act with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Integer deserialize(JsonParser p, DeserializationContext ctxt)
    throws IOException, JsonProcessingException {
  final int thisId = p.getIntValue();
  /* Set the instance counter to the current document's id + 1 if it isn't already higher.  This will (weakly)
   * ensure that any newly created documents don't collide with whatever we're reading in.
   *
   * TODO: these ids are awful, and are certainly something I expect to regret implementing.  We should use
   * something better, make ids cleanly transient, or try to get away from ids at all.
   */
  instanceCounter.getAndUpdate(x -> Integer.max(x, thisId + 1));
  return thisId;
}
 
Example 7
Source File: JSR310LocalDateDeserializer.java    From klask-io with GNU General Public License v3.0 5 votes vote down vote up
@Override
public LocalDate deserialize(JsonParser parser, DeserializationContext context) throws IOException {
    switch(parser.getCurrentToken()) {
        case START_ARRAY:
            if(parser.nextToken() == JsonToken.END_ARRAY) {
                return null;
            }
            int year = parser.getIntValue();

            parser.nextToken();
            int month = parser.getIntValue();

            parser.nextToken();
            int day = parser.getIntValue();

            if(parser.nextToken() != JsonToken.END_ARRAY) {
                throw context.wrongTokenException(parser, JsonToken.END_ARRAY, "Expected array to end.");
            }
            return LocalDate.of(year, month, day);

        case VALUE_STRING:
            String string = parser.getText().trim();
            if(string.length() == 0) {
                return null;
            }
            return LocalDate.parse(string, ISO_DATE_OPTIONAL_TIME);
        default:
            throw context.wrongTokenException(parser, JsonToken.START_ARRAY, "Expected array or string.");
    }
}
 
Example 8
Source File: IntBeanTable.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * for attribute value2 parsing
 */
public static Integer[] parseValue2(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();
    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=CollectionUtils.asIntegerArray(collection);
    }
    return result;
  } catch(Exception e) {
    e.printStackTrace();
    throw(new KriptonRuntimeException(e.getMessage()));
  }
}
 
Example 9
Source File: AbstractEmoFieldUDF.java    From emodb with Apache License 2.0 5 votes vote down vote up
protected BooleanWritable narrowToBoolean(JsonParser parser)
        throws IOException {
    switch (parser.getCurrentToken()) {
        case VALUE_TRUE:
            return new BooleanWritable(true);
        case VALUE_FALSE:
            return new BooleanWritable(false);
        case VALUE_NUMBER_INT:
            return new BooleanWritable(parser.getIntValue() != 0);
        case VALUE_NUMBER_FLOAT:
            return new BooleanWritable(parser.getFloatValue() != 0);
        default:
            return null;
    }
}
 
Example 10
Source File: IntegerNodeCalc.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
static NodeCalc parseJson(JsonParser parser) throws IOException {
    JsonToken token;
    while ((token = parser.nextToken()) != null) {
        if (token == JsonToken.VALUE_NUMBER_INT) {
            return new IntegerNodeCalc(parser.getIntValue());
        } else {
            throw NodeCalc.createUnexpectedToken(token);
        }
    }
    throw new TimeSeriesException("Invalid integer node calc JSON");
}
 
Example 11
Source File: IntBeanTable.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * for attribute value parsing
 */
public static int[] 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();
    int[] 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=CollectionUtils.asIntegerTypeArray(collection);
    }
    return result;
  } catch(Exception e) {
    e.printStackTrace();
    throw(new KriptonRuntimeException(e.getMessage()));
  }
}
 
Example 12
Source File: AbstractEmoFieldUDF.java    From emodb with Apache License 2.0 5 votes vote down vote up
protected FloatWritable narrowToFloat(JsonParser parser)
        throws IOException {
    switch (parser.getCurrentToken()) {
        case VALUE_NUMBER_INT:
            return new FloatWritable(parser.getIntValue());
        case VALUE_NUMBER_FLOAT:
            return new FloatWritable(parser.getFloatValue());
        default:
            return null;
    }
}
 
Example 13
Source File: QueryResultWithKeysParser.java    From icure-backend with GNU General Public License v2.0 5 votes vote down vote up
private void parseResult(JsonParser jp) throws IOException {
	if (jp.nextToken() != JsonToken.START_OBJECT) {
		throw new DbAccessException("Expected data to start with an Object");
	}

	Map<String, String> errorFields = new HashMap<String, String>();
	// Issue #98: Can't assume order of JSON fields.
	while (jp.nextValue() != JsonToken.END_OBJECT) {
		String currentName = jp.getCurrentName();
		if (OFFSET_FIELD_NAME.equals(currentName)) {
			offset = jp.getIntValue();
		} else if (TOTAL_ROWS_FIELD_NAME.equals(currentName)) {
			totalRows = jp.getIntValue();
		} else if (ROWS_FIELD_NAME.equals(currentName)) {
			rows = new ArrayList<T>();
			ids = new ArrayList<>();
			keys = new ArrayList<>();
			parseRows(jp);
		} else if (UPDATE_SEQUENCE_NAME.equals(currentName)) {
			updateSequence = jp.getLongValue();
		} else {
			// Handle cloudant errors.
			errorFields.put(jp.getCurrentName(), jp.getText());
		}
	}

	if (!errorFields.isEmpty()) {
		JsonNode error = mapper.convertValue(errorFields, JsonNode.class);
		throw new DbAccessException(error.toString());
	}
}
 
Example 14
Source File: UserStatusDeserializer.java    From weixin-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public UserStatus deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
    int status = jsonParser.getIntValue();
    if (1 == status) return UserStatus.FOLLOWED;
    if (2 == status) return UserStatus.SUSPEND;
    if (4 == status) return UserStatus.UN_FOLLOWED;

    return UserStatus.UNKNOWN;
}
 
Example 15
Source File: StackTraceElementDeserializer.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public StackTraceElement deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
{
    JsonToken t = p.getCurrentToken();
    // Must get an Object
    if (t == JsonToken.START_OBJECT) {
        String className = "", methodName = "", fileName = "";
        // Java 9 adds couple more things
        String moduleName = null, moduleVersion = null;
        String classLoaderName = null;
        int lineNumber = -1;

        while ((t = p.nextValue()) != JsonToken.END_OBJECT) {
            String propName = p.getCurrentName();
            // TODO: with Java 8, convert to switch
            if ("className".equals(propName)) {
                className = p.getText();
            } else if ("classLoaderName".equals(propName)) {
                classLoaderName = p.getText();
            } else if ("fileName".equals(propName)) {
                fileName = p.getText();
            } else if ("lineNumber".equals(propName)) {
                if (t.isNumeric()) {
                    lineNumber = p.getIntValue();
                } else {
                    lineNumber = _parseIntPrimitive(p, ctxt);
                }
            } else if ("methodName".equals(propName)) {
                methodName = p.getText();
            } else if ("nativeMethod".equals(propName)) {
                // no setter, not passed via constructor: ignore
            } else if ("moduleName".equals(propName)) {
                moduleName = p.getText();
            } else if ("moduleVersion".equals(propName)) {
                moduleVersion = p.getText();
            } else if ("declaringClass".equals(propName)
                    || "format".equals(propName)) {
                // 01-Nov-2017: [databind#1794] Not sure if we should but... let's prune it for now
                ;
            } else {
                handleUnknownProperty(p, ctxt, _valueClass, propName);
            }
            p.skipChildren(); // just in case we might get structured values
        }
        return constructValue(ctxt, className, methodName, fileName, lineNumber,
                moduleName, moduleVersion, classLoaderName);
    } else if (t == JsonToken.START_ARRAY && ctxt.isEnabled(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)) {
        p.nextToken();
        final StackTraceElement value = deserialize(p, ctxt);
        if (p.nextToken() != JsonToken.END_ARRAY) {
            handleMissingEndArrayForSingle(p, ctxt);
        }
        return value;
    }
    return (StackTraceElement) ctxt.handleUnexpectedToken(_valueClass, p);
}
 
Example 16
Source File: Record.java    From bitsy with Apache License 2.0 4 votes vote down vote up
public boolean checkObsolete(IGraphStore store, boolean isReorg, int lineNo, String fileName) {
    if (type == RecordType.T) {
        // Transaction boundaries are obsolete during reorg
        return isReorg;
    } else if (type == RecordType.L) {
        // A log is always obsolete
        return false;
    } else if ((type != RecordType.V) && (type != RecordType.E)) {
        throw new BitsyException(BitsyErrorCodes.INTERNAL_ERROR, "Unhanded record type: " + type);
    }

    // A V or E record
    UUID id = null;
    int version = -1;
    String state = null;
    JsonToken token;

    try {
        JsonParser parser = factory.createJsonParser(json);

        while ((token = parser.nextToken()) != JsonToken.END_OBJECT) {
            // Find the version
            if (token == JsonToken.FIELD_NAME) {
                if (parser.getCurrentName().equals("id")) {
                    parser.nextToken();
                    id = UUID.fromString(parser.getText());
                    continue;
                }

                if (parser.getCurrentName().equals("v")) {
                    parser.nextToken();
                    version = parser.getIntValue();
                    continue;
                }

                if (parser.getCurrentName().equals("s")) {
                    parser.nextToken();
                    state = parser.getText();

                    // No need to proceed further
                    break;
                }
            }
        }

        if ((id == null) || (version == -1) || (state == null)) {
            throw new BitsyException(BitsyErrorCodes.INTERNAL_ERROR, "Unable to parse record '" + json + "' in file " + fileName + " at line " + lineNo);
        }

        if (state.equals("D")) {
            // Deleted -- can be ignored only on re-orgs
            return isReorg;
        } else {
            if (type == RecordType.V) {
                VertexBean curV = store.getVertex(id);
                if (curV == null) {
                    // Doesn't exist anymore, probably deleted later
                    return true;
                } else if (curV.getVersion() != version) {
                    // Obsolete
                    return true;
                } else {
                    // Good to go
                    return false;
                }
            } else {
                assert (type == RecordType.E);

                EdgeBean curE = store.getEdge(id);
                if (curE == null) {
                    // Doesn't exist anymore, probably deleted later
                    return true;
                } else if (curE.getVersion() != version) {
                    // Obsolete
                    return true;
                } else {
                    // Good to go
                    return false;
                }
            }
        }
    } catch (Exception e) {
        throw new BitsyException(BitsyErrorCodes.INTERNAL_ERROR, "Possible bug in code. Error serializing line '" + json + "' in file " + fileName + " at line " + lineNo, e);
    }
}
 
Example 17
Source File: PrimitiveKVHandler.java    From jackson-datatypes-collections with Apache License 2.0 4 votes vote down vote up
public int value(DeserializationContext ctx, JsonParser parser) throws IOException {
    return parser.getIntValue();
}
 
Example 18
Source File: KeyProtectionsDeserializer.java    From webauthn4j with Apache License 2.0 4 votes vote down vote up
@Override
public KeyProtections deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    return new KeyProtections(p.getIntValue());
}
 
Example 19
Source File: ThumbnailBindMap.java    From kripton with Apache License 2.0 4 votes vote down vote up
/**
 * parse with jackson
 */
@Override
public Thumbnail parseOnJackson(JsonParser jacksonParser) throws Exception {
  Thumbnail instance = new Thumbnail();
  String fieldName;
  if (jacksonParser.currentToken() == null) {
    jacksonParser.nextToken();
  }
  if (jacksonParser.currentToken() != JsonToken.START_OBJECT) {
    jacksonParser.skipChildren();
    return instance;
  }
  while (jacksonParser.nextToken() != JsonToken.END_OBJECT) {
    fieldName = jacksonParser.getCurrentName();
    jacksonParser.nextToken();

    // Parse fields:
    switch (fieldName) {
        case "height":
          // field height (mapped with "height")
          if (jacksonParser.currentToken()!=JsonToken.VALUE_NULL) {
            instance.height=jacksonParser.getIntValue();
          }
        break;
        case "url":
          // field url (mapped with "url")
          if (jacksonParser.currentToken()!=JsonToken.VALUE_NULL) {
            instance.url=UrlUtils.read(jacksonParser.getText());
          }
        break;
        case "width":
          // field width (mapped with "width")
          if (jacksonParser.currentToken()!=JsonToken.VALUE_NULL) {
            instance.width=jacksonParser.getIntValue();
          }
        break;
        default:
          jacksonParser.skipChildren();
        break;}
  }
  return instance;
}
 
Example 20
Source File: Bean03BindMap.java    From kripton with Apache License 2.0 4 votes vote down vote up
/**
 * parse with jackson
 */
@Override
public Bean03 parseOnJackson(JsonParser jacksonParser) throws Exception {
  Bean03 instance = new Bean03();
  String fieldName;
  if (jacksonParser.currentToken() == null) {
    jacksonParser.nextToken();
  }
  if (jacksonParser.currentToken() != JsonToken.START_OBJECT) {
    jacksonParser.skipChildren();
    return instance;
  }
  while (jacksonParser.nextToken() != JsonToken.END_OBJECT) {
    fieldName = jacksonParser.getCurrentName();
    jacksonParser.nextToken();

    // Parse fields:
    switch (fieldName) {
        case "miscellaneus":
          // field miscellaneus (mapped with "miscellaneus")
          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);
            }
            instance.setMiscellaneus(collection);
          }
        break;
        case "type":
          // field type (mapped with "type")
          if (jacksonParser.currentToken()!=JsonToken.VALUE_NULL) {
            instance.setType(jacksonParser.getText());
          }
        break;
        default:
          jacksonParser.skipChildren();
        break;}
  }
  return instance;
}