Java Code Examples for org.codehaus.jackson.JsonParser

The following examples show how to use org.codehaus.jackson.JsonParser. These examples are extracted from open source projects. 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 Project: binlake   Source File: JsonUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static JsonNode parseJson(String json) throws Exception {

		ObjectMapper mapper = new ObjectMapper();	
		JsonFactory f = new MappingJsonFactory();
		JsonParser jp = null;
		JsonNode rootNode = null;
		try {
			jp = f.createJsonParser(json);
			rootNode = mapper.readTree(jp);
		} catch (Exception e) {
			throw e;
		} finally {
			if (jp != null)
				jp.close();
		}
		return rootNode;
	}
 
Example 2
@SuppressWarnings("unchecked")
protected BackportedJacksonMappingIterator(JavaType type, JsonParser jp, DeserializationContext ctxt, JsonDeserializer<?> deser) {
    _type = type;
    _parser = jp;
    _context = ctxt;
    _deserializer = (JsonDeserializer<T>) deser;

    /* One more thing: if we are at START_ARRAY (but NOT root-level
     * one!), advance to next token (to allow matching END_ARRAY)
     */
    if (jp != null && jp.getCurrentToken() == JsonToken.START_ARRAY) {
        JsonStreamContext sc = jp.getParsingContext();
        // safest way to skip current token is to clear it (so we'll advance soon)
        if (!sc.inRoot()) {
            jp.clearCurrentToken();
        }
    }
}
 
Example 3
Source Project: urule   Source File: AbstractJsonDeserializer.java    License: Apache License 2.0 6 votes vote down vote up
private void buildScoreRule(JsonParser jsonParser,JsonNode ruleNode,ScoreRule rule){
	rule.setScoringBean(JsonUtils.getJsonValue(ruleNode, "scoringBean"));
	AssignTargetType assignTargetType=AssignTargetType.valueOf(JsonUtils.getJsonValue(ruleNode, "assignTargetType"));
	rule.setAssignTargetType(assignTargetType);
	rule.setVariableCategory(JsonUtils.getJsonValue(ruleNode, "variableCategory"));
	rule.setVariableName(JsonUtils.getJsonValue(ruleNode, "variableName"));
	rule.setVariableLabel(JsonUtils.getJsonValue(ruleNode, "variableLabel"));
	String datatypeStr=JsonUtils.getJsonValue(ruleNode, "datatype");
	if(StringUtils.isNotBlank(datatypeStr)){
		rule.setDatatype(Datatype.valueOf(datatypeStr));
	}
	try{
		JsonNode knowledgePackageWrapperNode=ruleNode.get("knowledgePackageWrapper");
		ObjectMapper mapper = (ObjectMapper)jsonParser.getCodec();
		KnowledgePackageWrapper wrapper=mapper.readValue(knowledgePackageWrapperNode, KnowledgePackageWrapper.class);
		wrapper.buildDeserialize();
		rule.setKnowledgePackageWrapper(wrapper);			
	}catch(Exception ex){
		throw new RuleException(ex);
	}
	
}
 
Example 4
Source Project: hadoop   Source File: StateDeserializer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public StatePair deserialize(JsonParser parser, 
                             DeserializationContext context)
throws IOException, JsonProcessingException {
  ObjectMapper mapper = (ObjectMapper) parser.getCodec();
  // set the state-pair object tree
  ObjectNode statePairObject = (ObjectNode) mapper.readTree(parser);
  Class<?> stateClass = null;
  
  try {
    stateClass = 
      Class.forName(statePairObject.get("className").getTextValue().trim());
  } catch (ClassNotFoundException cnfe) {
    throw new RuntimeException("Invalid classname!", cnfe);
  }
  
  String stateJsonString = statePairObject.get("state").toString();
  State state = (State) mapper.readValue(stateJsonString, stateClass);
  
  return new StatePair(state);
}
 
Example 5
Source Project: hadoop   Source File: StatePool.java    License: Apache License 2.0 6 votes vote down vote up
private void read(DataInput in) throws IOException {
  ObjectMapper mapper = new ObjectMapper();
  mapper.configure(
      DeserializationConfig.Feature.CAN_OVERRIDE_ACCESS_MODIFIERS, true);
  
  // define a module
  SimpleModule module = new SimpleModule("State Serializer",  
      new Version(0, 1, 1, "FINAL"));
  // add the state deserializer
  module.addDeserializer(StatePair.class, new StateDeserializer());

  // register the module with the object-mapper
  mapper.registerModule(module);

  JsonParser parser = 
    mapper.getJsonFactory().createJsonParser((DataInputStream)in);
  StatePool statePool = mapper.readValue(parser, StatePool.class);
  this.setStates(statePool.getStates());
  parser.close();
}
 
Example 6
Source Project: elasticsearch-hadoop   Source File: JacksonJsonParser.java    License: Apache License 2.0 6 votes vote down vote up
private NumberType convertNumberType(JsonParser.NumberType numberType) {
    switch (numberType) {
    case INT:
        return NumberType.INT;
    case LONG:
        return NumberType.LONG;
    case FLOAT:
        return NumberType.FLOAT;
    case DOUBLE:
        return NumberType.DOUBLE;
    case BIG_INTEGER:
        return NumberType.DOUBLE;
    case BIG_DECIMAL:
        return NumberType.DOUBLE;
    }
    throw new EsHadoopSerializationException("No matching token for number_type [" + numberType + "]");
}
 
Example 7
Source Project: jwala   Source File: JsonUpdateWebServer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public JsonUpdateWebServer deserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException {

    final ObjectCodec obj = jp.getCodec();
    final JsonNode node = obj.readTree(jp).get(0);

    final Set<String> groupIds = deserializeGroupIdentifiers(node);
    return new JsonUpdateWebServer(node.get("webserverId").getValueAsText(),
                                   node.get("webserverName").getTextValue(),
                                   node.get("hostName").getTextValue(),
                                   node.get("portNumber").getValueAsText(),
                                   node.get("httpsPort").getValueAsText(),
                                   groupIds,
                                   node.get("statusPath").getTextValue(),
                                   node.get("apacheHttpdMediaId").getTextValue());
}
 
Example 8
private com.esri.core.geometry.Geometry constructGeometry(com.esri.ges.spatial.Geometry geo) throws Exception
{
	try{
		String jsonIn = geo.toJson();
		JsonFactory jf = new JsonFactory();
		JsonParser jp = jf.createJsonParser(jsonIn);
		MapGeometry mgeo = GeometryEngine.jsonToGeometry(jp);
		com.esri.core.geometry.Geometry geoIn= mgeo.getGeometry();
		return GeometryEngine.project(geoIn, srIn, srBuffer);
	}
	catch(Exception e)
	{
		LOG.error(e.getMessage());
		LOG.error(e.getStackTrace());
		throw(e);
	}
}
 
Example 9
Source Project: big-c   Source File: StateDeserializer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public StatePair deserialize(JsonParser parser, 
                             DeserializationContext context)
throws IOException, JsonProcessingException {
  ObjectMapper mapper = (ObjectMapper) parser.getCodec();
  // set the state-pair object tree
  ObjectNode statePairObject = (ObjectNode) mapper.readTree(parser);
  Class<?> stateClass = null;
  
  try {
    stateClass = 
      Class.forName(statePairObject.get("className").getTextValue().trim());
  } catch (ClassNotFoundException cnfe) {
    throw new RuntimeException("Invalid classname!", cnfe);
  }
  
  String stateJsonString = statePairObject.get("state").toString();
  State state = (State) mapper.readValue(stateJsonString, stateClass);
  
  return new StatePair(state);
}
 
Example 10
Source Project: incubator-hivemall   Source File: JsonSerdeUtils.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
private static List<Object> parseArray(@Nonnull final JsonParser p,
        @CheckForNull final List<TypeInfo> columnTypes)
        throws HCatException, IOException, SerDeException {
    Preconditions.checkNotNull(columnTypes, "columnTypes MUST NOT be null",
        SerDeException.class);
    if (columnTypes.size() != 1) {
        throw new IOException("Expected a single array but go " + columnTypes);
    }

    TypeInfo elemType = columnTypes.get(0);
    HCatSchema schema = HCatSchemaUtils.getHCatSchema(elemType);

    HCatFieldSchema listSchema = schema.get(0);
    HCatFieldSchema elemSchema = listSchema.getArrayElementSchema().get(0);

    final List<Object> arr = new ArrayList<Object>();
    while (p.nextToken() != JsonToken.END_ARRAY) {
        arr.add(extractCurrentField(p, elemSchema, true));
    }
    return arr;
}
 
Example 11
Source Project: incubator-hivemall   Source File: JsonSerdeUtils.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
private static Object parseValue(@Nonnull final JsonParser p)
        throws JsonParseException, IOException {
    final JsonToken t = p.getCurrentToken();
    switch (t) {
        case VALUE_FALSE:
            return Boolean.FALSE;
        case VALUE_TRUE:
            return Boolean.TRUE;
        case VALUE_NULL:
            return null;
        case VALUE_STRING:
            return p.getText();
        case VALUE_NUMBER_FLOAT:
            return p.getDoubleValue();
        case VALUE_NUMBER_INT:
            return p.getIntValue();
        default:
            throw new IOException("Unexpected token: " + t);
    }
}
 
Example 12
Source Project: incubator-hivemall   Source File: HiveJsonStructReader.java    License: Apache License 2.0 6 votes vote down vote up
private static void skipValue(JsonParser parser) throws JsonParseException, IOException {
    int array = 0;
    int object = 0;
    do {
        JsonToken currentToken = parser.getCurrentToken();
        if (currentToken == JsonToken.START_ARRAY) {
            array++;
        }
        if (currentToken == JsonToken.END_ARRAY) {
            array--;
        }
        if (currentToken == JsonToken.START_OBJECT) {
            object++;
        }
        if (currentToken == JsonToken.END_OBJECT) {
            object--;
        }

        parser.nextToken();

    } while (array > 0 || object > 0);
}
 
Example 13
Source Project: incubator-hivemall   Source File: HiveJsonStructReader.java    License: Apache License 2.0 6 votes vote down vote up
private Object parsePrimitive(JsonParser parser, PrimitiveObjectInspector oi)
        throws SerDeException, IOException {
    JsonToken currentToken = parser.getCurrentToken();
    if (currentToken == null) {
        return null;
    }
    try {
        switch (parser.getCurrentToken()) {
            case VALUE_FALSE:
            case VALUE_TRUE:
            case VALUE_NUMBER_INT:
            case VALUE_NUMBER_FLOAT:
            case VALUE_STRING:
                return getObjectOfCorrespondingPrimitiveType(parser.getText(), oi);
            case VALUE_NULL:
                return null;
            default:
                throw new SerDeException("unexpected token type: " + currentToken);
        }
    } finally {
        parser.nextToken();
    }
}
 
Example 14
private int getCurrentRetrainingThreshold() throws Exception {
	try {
		String retrainingThreshold = this.getRetainingThreshold();

		ObjectMapper mapper = JacksonWrapper.getObjectMapper();
		JsonFactory factory = mapper.getJsonFactory(); // since 2.1 use
														// mapper.getFactory()
														// instead
		JsonParser jp = factory.createJsonParser(retrainingThreshold);
		JsonNode actualObj = mapper.readTree(jp);

		JsonNode nameNode = actualObj.get("sampleCountThreshold");

		int sampleCountThreshold = Integer.parseInt(nameNode.asText());

		return sampleCountThreshold;
	} catch (Exception e) {
		logger.error("Exception while getting CurrentRetrainingThreshold", e);
		return 50;

	}
}
 
Example 15
Source Project: io   Source File: BarFileUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * barファイルエントリからJSONファイルを読み込む.
 * @param <T> JSONMappedObject
 * @param inStream barファイルエントリのInputStream
 * @param entryName entryName
 * @param clazz clazz
 * @return JSONファイルから読み込んだオブジェクト
 * @throws IOException JSONファイル読み込みエラー
 */
public static <T> T readJsonEntry(
        InputStream inStream, String entryName, Class<T> clazz) throws IOException {
    JsonParser jp = null;
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory f = new JsonFactory();
    jp = f.createJsonParser(inStream);
    JsonToken token = jp.nextToken(); // JSONルート要素("{")
    Pattern formatPattern = Pattern.compile(".*/+(.*)");
    Matcher formatMatcher = formatPattern.matcher(entryName);
    String jsonName = formatMatcher.replaceAll("$1");
    T json = null;
    if (token == JsonToken.START_OBJECT) {
        try {
            json = mapper.readValue(jp, clazz);
        } catch (UnrecognizedPropertyException ex) {
            throw DcCoreException.BarInstall.JSON_FILE_FORMAT_ERROR.params(jsonName);
        }
    } else {
        throw DcCoreException.BarInstall.JSON_FILE_FORMAT_ERROR.params(jsonName);
    }
    return json;
}
 
Example 16
Source Project: io   Source File: EventResource.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * リクエストボディを解析してEventオブジェクトを取得する.
 * @param reader Http入力ストリーム
 * @return 解析したEventオブジェクト
 */
protected JSONEvent getRequestBody(final Reader reader) {
    JSONEvent event = null;
    JsonParser jp = null;
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory f = new JsonFactory();
    try {
        jp = f.createJsonParser(reader);
        JsonToken token = jp.nextToken(); // JSONルート要素("{")
        if (token == JsonToken.START_OBJECT) {
            event = mapper.readValue(jp, JSONEvent.class);
        } else {
            throw DcCoreException.Event.JSON_PARSE_ERROR;
        }
    } catch (IOException e) {
        throw DcCoreException.Event.JSON_PARSE_ERROR;
    }
    return event;
}
 
Example 17
Source Project: io   Source File: JSONManifestTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * manifest.jsonのschema値がURL形式である場合trueが返却されること.
 * @throws IOException IOException
 */
@SuppressWarnings("unchecked")
@Test
public void manifest_jsonのschema値がURL形式である場合trueが返却されること() throws IOException {
    JsonFactory f = new JsonFactory();
    JSONObject json = new JSONObject();
    json.put("bar_version", "1");
    json.put("box_version", "1");
    json.put("DefaultPath", "boxName");
    json.put("schema", "http://app1.example.com/");
    JsonParser jp = f.createJsonParser(json.toJSONString());
    ObjectMapper mapper = new ObjectMapper();
    jp.nextToken();

    JSONManifest manifest = mapper.readValue(jp, JSONManifest.class);

    assertTrue(manifest.checkSchema());
}
 
Example 18
Source Project: cxf   Source File: HelloWorldIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJsonRoundtrip() throws Exception {
    List<Object> providers = new ArrayList<>();
    providers.add(new org.codehaus.jackson.jaxrs.JacksonJsonProvider());
    JsonBean inputBean = new JsonBean();
    inputBean.setVal1("Maple");
    WebClient client = WebClient.create(endpointUrl + "/hello/jsonBean", providers);
    Response r = client.accept("application/json")
        .type("application/json")
        .post(inputBean);
    assertEquals(Response.Status.OK.getStatusCode(), r.getStatus());
    MappingJsonFactory factory = new MappingJsonFactory();
    JsonParser parser = factory.createJsonParser((InputStream)r.getEntity());
    JsonBean output = parser.readValueAs(JsonBean.class);
    assertEquals("Maple", output.getVal2());
}
 
Example 19
Source Project: io   Source File: BarFileValidateTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * box_versionを指定しない場合に例外がスローされる.
 */
@Test
@SuppressWarnings({"unchecked" })
public void box_versionを指定しない場合に例外がスローされる() {
    JsonFactory f = new JsonFactory();
    JSONObject json = new JSONObject();
    json.put("bar_version", "1");
    json.put("DefaultPath", "boxName");
    json.put("schema", "http://app1.example.com");

    try {
        JsonParser jp = f.createJsonParser(json.toJSONString());
        ObjectMapper mapper = new ObjectMapper();
        jp.nextToken();

        TestBarRunner testBarRunner = new TestBarRunner();
        testBarRunner.manifestJsonValidate(jp, mapper);
    } catch (DcCoreException dce) {
        assertEquals(400, dce.getStatus());
        assertEquals("PR400-BI-0006", dce.getCode());
        return;
    } catch (Exception ex) {
        fail("Unexpected exception");
    }
    fail("DcCoreExceptionが返却されない");
}
 
Example 20
Source Project: io   Source File: BarFileValidateTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * DefaultPathを指定しない場合に例外がスローされる.
 */
@Test
@SuppressWarnings({"unchecked" })
public void DefaultPathを指定しない場合に例外がスローされる() {
    JsonFactory f = new JsonFactory();
    JSONObject json = new JSONObject();
    json.put("bar_version", "1");
    json.put("box_version", "1");
    json.put("schema", "http://app1.example.com");

    try {
        JsonParser jp = f.createJsonParser(json.toJSONString());
        ObjectMapper mapper = new ObjectMapper();
        jp.nextToken();

        TestBarRunner testBarRunner = new TestBarRunner();
        testBarRunner.manifestJsonValidate(jp, mapper);
    } catch (DcCoreException dce) {
        assertEquals(400, dce.getStatus());
        assertEquals("PR400-BI-0006", dce.getCode());
        return;
    } catch (Exception ex) {
        fail("Unexpected exception");
    }
    fail("DcCoreExceptionが返却されない");
}
 
Example 21
Source Project: jeecg   Source File: CustomJsonDateDeserializer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
	String text = jp.getText();

	if (StringUtils.hasText(text)) {
		try {
			if (text.indexOf(":") == -1 && text.length() == 10) {
				return this.dateFormat.parse(text);
			} else if (text.indexOf(":") > 0 && text.length() == 19) {
				return this.datetimeFormat.parse(text);
			} else {
				throw new IllegalArgumentException("Could not parse date, date format is error ");
			}
		} catch (ParseException ex) {
			IllegalArgumentException iae = new IllegalArgumentException("Could not parse date: " + ex.getMessage());
			iae.initCause(ex);
			throw iae;
		}
	} else {
		return null;
	}
}
 
Example 22
Source Project: ReactiveLab   Source File: BackendResponse.java    License: Apache License 2.0 5 votes vote down vote up
public static BackendResponse fromJson(InputStream inputStream) {
    try {
        JsonParser parser = jsonFactory.createJsonParser(inputStream);
        return parseBackendResponse(parser);
    } catch (Exception e) {
        throw new RuntimeException("Failed to parse JSON", e);
    }
}
 
Example 23
Source Project: jwala   Source File: JsonControlJvm.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public JsonControlJvm deserialize(final JsonParser jp,
                                  final DeserializationContext ctxt) throws IOException {

    final ObjectCodec obj = jp.getCodec();
    final JsonNode rootNode = obj.readTree(jp);
    final JsonNode operation = rootNode.get("controlOperation");

    return new JsonControlJvm(operation.getTextValue());
}
 
Example 24
Source Project: arcgis-runtime-demo-java   Source File: GeoJsonParser.java    License: Apache License 2.0 5 votes vote down vote up
public List<Geometry> parseGeometries(File file) {
  try {
    JsonParser parser = new JsonFactory().createJsonParser(file);
    return parseGeometries(parser);
  } catch (Exception ex) {
    throw new RuntimeException(ex);
  }
}
 
Example 25
Source Project: jwala   Source File: JsonControlWebServer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public JsonControlWebServer deserialize(final JsonParser jp,
                                  final DeserializationContext ctxt) throws IOException {

    final ObjectCodec obj = jp.getCodec();
    final JsonNode rootNode = obj.readTree(jp);
    final JsonNode operation = rootNode.get("controlOperation");

    return new JsonControlWebServer(operation.getTextValue());
}
 
Example 26
Source Project: spring-data-simpledb   Source File: JsonUnknownPropertyHandler.java    License: MIT License 5 votes vote down vote up
@Override
public boolean handleUnknownProperty(DeserializationContext ctxt, JsonDeserializer<?> deserializer,
		Object beanOrClass, String propertyName) throws IOException {
	JsonParser jsonParser = ctxt.getParser();
	LOG.warn("Unknown Json property: " + propertyName);
	jsonParser.skipChildren();

	return true;
}
 
Example 27
Source Project: jwala   Source File: PasswordDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException {
    if (StringUtils.isNotEmpty(jsonParser.getText())) {
        return new DecryptPassword().encrypt(jsonParser.getText());
    }
    return StringUtils.EMPTY;
}
 
Example 28
private String ConstructJsonMaskFromGeoEvent(GeoEvent ge) throws IOException
{
	com.esri.ges.spatial.Geometry eventgeo = ge.getGeometry();
	String json = eventgeo.toJson();
	JsonFactory jf = new JsonFactory();
	JsonParser jp = jf.createJsonParser(json);
	MapGeometry mgeo = GeometryEngine.jsonToGeometry(jp);
	Geometry geo = mgeo.getGeometry();
	Geometry maskGeo = GeometryEngine.project(geo, srIn, srBuffer);
	return GeometryEngine.geometryToJson(srBuffer, maskGeo);
}
 
Example 29
Source Project: elasticsearch-hadoop   Source File: JsonUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Map<String, Object> asMap(InputStream inputStream) {
    Map<String, Object> map;
    try {
        // create parser manually to lower Jackson requirements
        JsonParser jsonParser = MAPPER.getJsonFactory().createJsonParser(inputStream);
        map = MAPPER.readValue(jsonParser, Map.class);
    } catch (IOException ex) {
        throw new EsHadoopParsingException(ex);
    }
    return map;
}
 
Example 30
Source Project: ReactiveLab   Source File: BackendResponse.java    License: Apache License 2.0 5 votes vote down vote up
public static BackendResponse fromJson(String json) {
    try {
        JsonParser parser = jsonFactory.createJsonParser(json);
        return parseBackendResponse(parser);
    } catch (Exception e) {
        throw new RuntimeException("Failed to parse JSON", e);
    }
}