List of usage examples for com.fasterxml.jackson.core JsonParser getCodec
public abstract ObjectCodec getCodec();
From source file:pl.edu.pwr.iiar.zak.thermalKit.deserializers.HeaterUnitDeserializer.java
/** * Override main method which deserializes the JSON description of the heater to Java * object./* w ww . j av a 2 s. c om*/ * * @param jp JSON parser * @param deserializationContext Deserialization context * @return HeaterUnit obejct * @throws IOException * @throws JsonProcessingException */ @Override public HeaterUnit deserialize(JsonParser jp, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { JsonNode node = jp.getCodec().readTree(jp); HeaterUnit heaterUnit = new HeaterUnit(); try { heaterUnit.setType(node.get("type").asText()); } catch (JGeneriloException e) { e.printStackTrace(); } heaterUnit.setCLBSize((Integer) (node.get("CLBsize")).numberValue()); heaterUnit.setInstancesNum((Integer) (node.get("instancesNum")).numberValue()); heaterUnit.setInstances(deserializeThermalInstances((ArrayNode) node.get("instances"))); heaterUnit.setInternalNets( deserializeNets((ArrayNode) node.get("nets"), createInstancesHashMap(heaterUnit.getInstances()))); return heaterUnit; }
From source file:org.brutusin.json.impl.serializers.InputStreamDeserializer.java
@Override public T deserialize(JsonParser jp, com.fasterxml.jackson.databind.DeserializationContext dc) throws IOException, JsonProcessingException { SerializationContext ctx = SerializationContext.getCurrentContext(); if (ctx == null) { return null; }/*from w w w .j av a 2 s . c o m*/ TreeNode tree = jp.getCodec().readTree(jp); if (tree != null) { try { return (T) ctx.getInputStreamAndRegisterCount( JsonCodec.getInstance().parse(tree.toString(), String.class)); } catch (ParseException ex) { throw new RuntimeException(ex); } } return null; }
From source file:com.msopentech.odatajclient.engine.metadata.edm.v4.annotation.DynExprConstructDeserializer.java
private ExprConstruct parseConstOrEnumExprConstruct(final JsonParser jp) throws IOException { ExprConstruct result;/*from ww w . ja v a 2s. com*/ if (isAnnotationConstExprConstruct(jp)) { result = parseAnnotationConstExprConstruct(jp); } else { result = jp.getCodec().readValue(jp, DynExprConstruct.class); } jp.nextToken(); return result; }
From source file:com.google.gplus.serializer.util.GPlusPersonDeserializer.java
/** * Because the GooglePlus Person object contains complex objects within its hierarchy, we have to use * a custom deserializer// w w w.j a va2 s . c o m * * @param jsonParser * @param deserializationContext * @return The deserialized {@link com.google.api.services.plus.model.Person} object * @throws IOException * @throws JsonProcessingException */ @Override public Person deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { ObjectMapper m = StreamsJacksonMapper.getInstance(); JsonNode node = jsonParser.getCodec().readTree(jsonParser); Person person = new Person(); try { person.setCircledByCount((Integer) ((IntNode) node.get("circledByCount")).numberValue()); person.setDisplayName(node.get("displayName").asText()); person.setEtag(node.get("etag").asText()); person.setGender(node.get("gender").asText()); person.setId(node.get("id").asText()); Person.Image image = new Person.Image(); JsonNode imageNode = node.get("image"); image.setIsDefault(imageNode.get("isDefault").asBoolean()); image.setUrl(imageNode.get("url").asText()); person.setImage(image); person.setIsPlusUser(node.get("isPlusUser").asBoolean()); person.setKind(node.get("kind").asText()); JsonNode nameNode = node.get("name"); Person.Name name = m.readValue(m.writeValueAsString(nameNode), Person.Name.class); person.setName(name); person.setObjectType(node.get("objectType").asText()); List<Person.Organizations> organizations = Lists.newArrayList(); for (JsonNode orgNode : node.get("organizations")) { Person.Organizations org = m.readValue(m.writeValueAsString(orgNode), Person.Organizations.class); organizations.add(org); } person.setOrganizations(organizations); person.setUrl(node.get("url").asText()); person.setVerified(node.get("verified").asBoolean()); List<Person.Emails> emails = Lists.newArrayList(); for (JsonNode emailNode : node.get("emails")) { Person.Emails email = m.readValue(m.writeValueAsString(emailNode), Person.Emails.class); emails.add(email); } person.setTagline(node.get("tagline").asText()); person.setAboutMe(node.get("aboutMe").asText()); } catch (Exception e) { LOGGER.error("Exception while trying to deserialize a Person object: {}", e); } return person; }
From source file:windows.webservices.JsonDeserializer.Deserializer.java
@Override public E deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException { try {/*from w w w . j a va2s .com*/ JsonNode json = jp.getCodec().readTree(jp); if (StringUtils.isEmpty(json.toString()) || json.toString().length() < 4) { return getNullValue(dc); } E instance = classChild.newInstance(); ObjectMapper mapper = new ObjectMapper(); SimpleModule modul = new SimpleModule("parroquia") .addDeserializer(Parroquia.class, new ParroquiaDeserializer()) .addDeserializer(Semana.class, new SemanaDeserializer()) .addDeserializer(Animal.class, new AnimalDeserializer()) .addDeserializer(Semana.class, new SemanaDeserializer()) .addDeserializer(Especie.class, new EspecieDeserializer()) .addDeserializer(Persona.class, new PersonaDeserializer()) .addDeserializer(Permiso.class, new PermisoDeserializer()) .addDeserializer(Usuario.class, new UsuarioDeserializer()) .addDeserializer(Cliente.class, new ClienteDeserializer()) .addDeserializer(Municipio.class, new MunicipioDeserializer()) .addDeserializer(Animal_has_Caso.class, new Animal_has_CasoDeserializer()) .addDeserializer(Caso.class, new CasoDeserializer()) .addDeserializer(Novedades.class, new NovedadesDeserializer()) .addDeserializer(RegistroVacunacion.class, new RegistroVacunacionDeserializer()) .addDeserializer(RegistroVacunacion_has_Animal.class, new RegistroVacunacion_has_AnimalDeserializer()) .addDeserializer(Vacunacion.class, new VacunacionDeserializer()); mapper.registerModule(modul); for (Field field : ReflectionUtils.getAllFields(classChild)) { Object value = null; Iterator<String> it = json.fieldNames(); String column = null; String fieldName = field.getName(); JsonProperty property = field.getAnnotation(JsonProperty.class); if (property != null) { fieldName = property.value(); } while (it.hasNext()) { String name = it.next(); if (Objects.equals(name.trim(), fieldName)) { column = name; break; } } if (column == null) { System.out.println("No se reconoce la siguente columna : " + fieldName + " de : " + classChild.getSimpleName()); continue; } if (field.getType().equals(String.class)) { value = json.get(column).asText(); } else if (Collection.class.isAssignableFrom(field.getType())) { if (StringUtils.isNotEmpty(json.get(column).toString())) { ParameterizedType stringListType = (ParameterizedType) field.getGenericType(); Class<?> stringListClass = (Class<?>) stringListType.getActualTypeArguments()[0]; value = mapper.readValue(json.get(column).toString(), mapper.getTypeFactory().constructCollectionType(List.class, stringListClass)); } else { value = null; } } else if (!field.getType().equals(Date.class)) { try { value = mapper.convertValue(json.get(column), field.getType()); } catch (IllegalArgumentException ex) { value = null; } } else { String date = json.get(column).textValue(); try { if (date != null) { value = d.parse(date.replace("-", "/")); } } catch (ParseException ex) { Logger.getLogger(Deserializer.class.getName()).log(Level.SEVERE, null, ex); } } ReflectionUtils.runSetter(field, instance, value); } return instance; } catch (InstantiationException | IllegalAccessException ex) { Logger.getLogger(Deserializer.class.getName()).log(Level.SEVERE, null, ex); } return getNullValue(dc); }
From source file:com.ptoceti.osgi.obix.impl.converters.ObjDeserializer.java
@Override public Obj deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { ObjectMapper mapper = (ObjectMapper) jp.getCodec(); ObjectNode root = (ObjectNode) mapper.readTree(jp); Class<? extends Obj> objClass = null; Iterator<Entry<String, JsonNode>> elementsIterator = root.fields(); String isValue = null;//from w ww . j ava2 s. c o m String typeValue = null; while (elementsIterator.hasNext()) { Entry<String, JsonNode> element = elementsIterator.next(); String name = element.getKey(); if (name.equals("type")) typeValue = element.getValue().textValue(); if (name.equals("is")) isValue = element.getValue().textValue(); } if (typeValue != ObixNames.OBJ) { // native object to create if (typeValue == ObixNames.ABSTIME) { objClass = Abstime.class; } else if (typeValue.equals(ObixNames.BOOL)) { objClass = Bool.class; } else if (typeValue.equals(ObixNames.ENUM)) { objClass = Enum.class; } else if (typeValue.equals(ObixNames.ERR)) { objClass = Err.class; } else if (typeValue.equals(ObixNames.FEED)) { objClass = Feed.class; } else if (typeValue.equals(ObixNames.INT)) { objClass = Int.class; } else if (typeValue.equals(ObixNames.LIST)) { objClass = List.class; } else if (typeValue.equals(ObixNames.OP)) { objClass = Op.class; } else if (typeValue.equals(ObixNames.REAL)) { objClass = Real.class; } else if (typeValue.equals(ObixNames.REF)) { objClass = Ref.class; } else if (typeValue.equals(ObixNames.RELTIME)) { objClass = Reltime.class; } else if (typeValue.equals(ObixNames.STR)) { objClass = Str.class; } else if (typeValue.equals(ObixNames.URI)) { objClass = Uri.class; } else { objClass = getObixObjClassFromContract(isValue); } } else { objClass = getObixObjClassFromContract(isValue); } if (objClass == null) return null; return mapper.convertValue(root, objClass); }
From source file:com.msopentech.odatajclient.engine.data.json.JSONPropertyDeserializer.java
@Override protected JSONProperty doDeserializeV4(JsonParser parser, DeserializationContext ctxt) throws IOException, JsonProcessingException { final ObjectNode tree = (ObjectNode) parser.getCodec().readTree(parser); final JSONProperty property = new JSONProperty(); try {/*from w w w.ja v a 2 s.c o m*/ final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder(); final Document document = builder.newDocument(); Element content = document.createElement(ODataConstants.ELEM_PROPERTY); JsonNode subtree = null; if (tree.has(ODataConstants.JSON_VALUE)) { if (tree.has(v4AnnotationPrefix + ODataConstants.JSON_TYPE) && StringUtils.isBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) { content.setAttribute(ODataConstants.ATTR_M_TYPE, tree.get(v4AnnotationPrefix + ODataConstants.JSON_TYPE).asText()); } final JsonNode value = tree.get(ODataConstants.JSON_VALUE); if (value.isValueNode()) { content.appendChild(document.createTextNode(value.asText())); } else if (EdmSimpleType.isGeospatial(content.getAttribute(ODataConstants.ATTR_M_TYPE))) { subtree = tree.objectNode(); ((ObjectNode) subtree).put(ODataConstants.JSON_VALUE, tree.get(ODataConstants.JSON_VALUE)); if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) { ((ObjectNode) subtree).put(ODataConstants.JSON_VALUE + "@" + ODataConstants.JSON_TYPE, content.getAttribute(ODataConstants.ATTR_M_TYPE)); } } else { subtree = tree.get(ODataConstants.JSON_VALUE); } } else { subtree = tree; } if (subtree != null) { DOMTreeUtilsV4.buildSubtree(content, subtree); } final List<Node> children = XMLUtils.getChildNodes(content, Node.ELEMENT_NODE); if (children.size() == 1) { final Element value = (Element) children.iterator().next(); if (ODataConstants.JSON_VALUE.equals(XMLUtils.getSimpleName(value))) { if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) { value.setAttribute(ODataConstants.ATTR_M_TYPE, content.getAttribute(ODataConstants.ATTR_M_TYPE)); } content = value; } } property.setContent(content); } catch (ParserConfigurationException e) { throw new JsonParseException("Cannot build property", parser.getCurrentLocation(), e); } return property; }
From source file:org.apache.airavata.db.AbstractThriftDeserializer.java
@Override public T deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { final T instance = newInstance(); final ObjectMapper mapper = (ObjectMapper) jp.getCodec(); final ObjectNode rootNode = mapper.readTree(jp); final Iterator<Map.Entry<String, JsonNode>> iterator = rootNode.fields(); while (iterator.hasNext()) { final Map.Entry<String, JsonNode> currentField = iterator.next(); try {/*from w ww .j a v a 2 s. co m*/ /* * If the current node is not a null value, process it. Otherwise, * skip it. Jackson will treat the null as a 0 for primitive * number types, which in turn will make Thrift think the field * has been set. Also we ignore the MongoDB specific _id field */ if (!currentField.getKey().equalsIgnoreCase("_id") && currentField.getValue().getNodeType() != JsonNodeType.NULL) { final E field = getField( CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, currentField.getKey())); final JsonParser parser = currentField.getValue().traverse(); parser.setCodec(mapper); final Object value = mapper.readValue(parser, generateValueType(instance, field)); if (value != null) { log.debug(String.format("Field %s produced value %s of type %s.", currentField.getKey(), value, value.getClass().getName())); instance.setFieldValue(field, value); } else { log.debug("Field {} contains a null value. Skipping...", currentField.getKey()); } } else { log.debug("Field {} contains a null value. Skipping...", currentField.getKey()); } } catch (final NoSuchFieldException | IllegalArgumentException e) { log.error("Unable to de-serialize field '{}'.", currentField.getKey(), e); ctxt.mappingException(e.getMessage()); } } try { // Validate that the instance contains all required fields. validate(instance); } catch (final TException e) { log.error(String.format("Unable to deserialize JSON '%s' to type '%s'.", jp.getValueAsString(), instance.getClass().getName(), e)); ctxt.mappingException(e.getMessage()); } return instance; }
From source file:org.n52.tamis.core.json.deserialize.processes.ProcessesDeserializer.java
@Override public Processes_Tamis deserialize(JsonParser jsonParser, DeserializationContext deserContext) throws IOException, JsonProcessingException { logger.info("Start deserialization of extended WPS processSummaries document."); // initialization ObjectCodec codec = jsonParser.getCodec(); JsonNode node = codec.readTree(jsonParser); // create empty shortened CapabilitiesDocument. Processes_Tamis processes_short = new Processes_Tamis(); /*//w w w . ja v a 2s .c om * JSPON element "ProcessSummaries" is an array of process descriptions */ JsonNode processSummaries = node.get("ProcessSummaries"); transformAndAddProcessSummaries(processes_short, processSummaries); logger.info("Deserialization ended! The following processes description instance was created: {}", processes_short); return processes_short; }
From source file:org.dd4t.databind.serializers.json.ComponentPresentationDeserializer.java
@Override public ComponentPresentation deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException { final ObjectMapper mapper = (ObjectMapper) jsonParser.getCodec(); final ObjectNode root = mapper.readTree(jsonParser); final ComponentPresentation componentPresentation = getConcreteComponentPresentation(); if (!isConcreteClass(componentPresentation)) { return null; }/* w w w . j a v a 2s . c o m*/ final Iterator<Map.Entry<String, JsonNode>> fields = root.fields(); JsonNode rawComponentData = null; String viewModelName = null; while (fields.hasNext()) { final Map.Entry<String, JsonNode> element = fields.next(); final String key = element.getKey(); LOG.trace(element.getKey() + " " + element.getValue().toString()); if (key.equalsIgnoreCase(DataBindConstants.COMPONENT_NODE_NAME)) { LOG.debug("Fishing out Component Data"); rawComponentData = element.getValue(); LOG.trace("Data is: {}", rawComponentData); } else if (key.equalsIgnoreCase(DataBindConstants.COMPONENT_TEMPLATE_NODE_NAME)) { LOG.debug("Deserializing Component Template Data."); final JsonParser parser = element.getValue().traverse(); final ComponentTemplate componentTemplate = JsonDataBinder.getGenericMapper().readValue(parser, this.concreteComponentTemplateClass); componentPresentation.setComponentTemplate(componentTemplate); viewModelName = DataBindFactory.findComponentTemplateViewName(componentTemplate); LOG.debug("Found view model name: " + viewModelName); } else if (key.equalsIgnoreCase(DataBindConstants.IS_DYNAMIC_NODE)) { final String isDynamic = element.getValue().asText().toLowerCase(); setIsDynamic(componentPresentation, isDynamic); } else if (key.equalsIgnoreCase(DataBindConstants.ORDER_ON_PAGE_NODE)) { componentPresentation.setOrderOnPage(element.getValue().asInt()); } else if (key.equalsIgnoreCase(DataBindConstants.RENDERED_CONTENT_NODE)) { componentPresentation.setRenderedContent(element.getValue().asText()); } } if (rawComponentData == null) { LOG.error("No component data found."); return componentPresentation; } try { renderComponentData(componentPresentation, rawComponentData, viewModelName, DataBindFactory.getRootElementName(rawComponentData)); } catch (SerializationException e) { LOG.error(e.getLocalizedMessage(), e); throw new IOException(e); } return componentPresentation; }