List of usage examples for com.fasterxml.jackson.core JsonParser getText
public abstract String getText() throws IOException, JsonParseException;
From source file:org.onosproject.north.aaa.api.parser.impl.ApplicationParser.java
public Application jsonToApplication(JsonParser jp) throws ParseException, IOException { Application.Builder builder = Application.builder(); while (true) { JsonToken token = jp.nextToken(); if (JsonToken.END_OBJECT.equals(token)) { // bail out break; }//from w w w .j ava 2 s . c o m if (JsonToken.FIELD_NAME.equals(token) && "appId".equals(jp.getCurrentName())) { jp.nextToken(); builder.buildAppId(jp.getText()); } else if (JsonToken.FIELD_NAME.equals(token) && "appDesc".equals(jp.getCurrentName())) { jp.nextToken(); builder.buildAppDesc(jp.getText()); } else if (JsonToken.FIELD_NAME.equals(token) && "appRoles".equals(jp.getCurrentName())) { jp.nextToken(); String roles = jp.getText(); if ("admin".equals(roles) || "normal".equals(roles) || "security".equals(roles)) { builder.buildAppRoles(roles); } else { // bail out throw new ParseException("appRoles must be set to \"admin\", \"normal\" or \"security\""); } } else if (JsonToken.FIELD_NAME.equals(token) && "devId".equals(jp.getCurrentName())) { jp.nextToken(); builder.buildDevId(jp.getText()); } else if (JsonToken.FIELD_NAME.equals(token) && "clientId".equals(jp.getCurrentName())) { jp.nextToken(); builder.buildClientId(jp.getText()); } } return builder.buildAll(); }
From source file:org.messic.server.api.tagwizard.discogs.DiscogsTAGWizardPlugin.java
@Override public List<Album> getAlbumInfo(Album albumHelpInfo, File[] files) { if (albumHelpInfo == null || (albumHelpInfo.name == null && albumHelpInfo.author == null) || ((albumHelpInfo.name != null && albumHelpInfo.name.length() <= 0) && (albumHelpInfo.author != null && albumHelpInfo.author.length() <= 0))) { return new ArrayList<Album>(); }/* www. j a va2s.c o m*/ String baseURL = "http://api.discogs.com/database/search?type=release"; try { if (albumHelpInfo.name != null) { baseURL = baseURL + "&release_title=" + URLEncoder.encode(albumHelpInfo.name, "UTF-8") + ""; } if (albumHelpInfo.author != null) { baseURL = baseURL + "&artist=" + URLEncoder.encode(albumHelpInfo.author, "UTF-8") + ""; } URL url = new URL(baseURL); Proxy proxy = getProxy(); URLConnection uc = (proxy != null ? url.openConnection(proxy) : url.openConnection()); uc.setRequestProperty("User-Agent", "Messic/1.0 +http://spheras.github.io/messic/"); ArrayList<Album> result = new ArrayList<Album>(); JsonFactory jsonFactory = new JsonFactory(); // or, for data binding, JsonParser jParser = jsonFactory.createParser(uc.getInputStream()); while (jParser.nextToken() != null) { String fieldname = jParser.getCurrentName(); if ("id".equals(fieldname)) { jParser.nextToken(); String id = jParser.getText(); // one second per petition allowed by discogs Thread.sleep(1000); Album album = getAlbum(id); result.add(album); } } return result; } catch (Exception e) { log.error("failed!", e); } return null; }
From source file:com.cedarsoft.serialization.jackson.AbstractJacksonSerializer.java
/** * Deserializes the enumeration//from w w w . j a v a 2 s . com * * @param enumClass the enum class * @param propertyName the property name * @param parser the parser * @param <T> the type * @return the deserialized enum * * @throws IOException */ @Nonnull public <T extends Enum<T>> T deserializeEnum(@Nonnull Class<T> enumClass, @Nonnull String propertyName, @Nonnull JsonParser parser) throws IOException { JacksonParserWrapper wrapper = new JacksonParserWrapper(parser); wrapper.nextFieldValue(propertyName); return Enum.valueOf(enumClass, parser.getText()); }
From source file:org.apache.ode.jacob.soup.jackson.ChannelProxyDeserializer.java
@Override public Channel deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { String type = null;//from w ww . j a v a 2s .c o m int id = -1; while (jp.nextToken() != JsonToken.END_OBJECT) { String fieldname = jp.getCurrentName(); if (jp.getCurrentToken() == JsonToken.FIELD_NAME) { // if we're not already on the field, advance by one. jp.nextToken(); } if ("channelType".equals(fieldname)) { type = jp.getText(); } else if ("channelId".equals(fieldname)) { id = jp.getIntValue(); } } if (type == null) { throw ctxt.mappingException(Channel.class); } if (id < 0) { throw ctxt.mappingException(Channel.class); } try { CommChannel cchannel = new CommChannel(ctxt.findClass(type)); cchannel.setId(id); return (Channel) ChannelFactory.createChannel(cchannel, cchannel.getType()); } catch (ClassNotFoundException e) { throw ctxt.instantiationException(Channel.class, e); } }
From source file:com.sdl.odata.unmarshaller.json.JsonLinkUnmarshaller.java
@Override protected String getToEntityId(ODataRequestContext requestContext) throws ODataUnmarshallingException { // The body is expected to contain a single entity reference // See OData JSON specification chapter 13 String bodyText;//from ww w. j a va 2 s .c o m try { bodyText = requestContext.getRequest().getBodyText(StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { throw new ODataSystemException("UTF-8 is not supported", e); } String idValue = null; try { JsonParser parser = new JsonFactory().createParser(bodyText); while (idValue == null && !parser.isClosed()) { JsonToken token = parser.nextToken(); if (token == null) { break; } if (token.equals(JsonToken.FIELD_NAME) && parser.getCurrentName().equals(JsonConstants.ID)) { token = parser.nextToken(); if (token.equals(JsonToken.VALUE_STRING)) { idValue = parser.getText(); } } } } catch (IOException e) { throw new ODataUnmarshallingException("Error while parsing JSON data", e); } if (isNullOrEmpty(idValue)) { throw new ODataUnmarshallingException("The JSON object in the body has no '@odata.id' value," + " or the value is empty. The JSON object in the body must have an '@odata.id' value" + " that refers to the entity to link to."); } return idValue; }
From source file:org.emfjson.jackson.tests.custom.CustomDeserializersTest.java
@Test public void testDeserializeReferenceAsStrings() throws JsonProcessingException { EMFModule module = new EMFModule(); module.configure(EMFModule.Feature.OPTION_USE_ID, true); module.configure(EMFModule.Feature.OPTION_SERIALIZE_TYPE, false); module.setReferenceDeserializer(new JsonDeserializer<ReferenceEntry>() { @Override/*from ww w. j a va 2s . c om*/ public ReferenceEntry deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { final EObject parent = EMFContext.getParent(ctxt); final EReference reference = EMFContext.getReference(ctxt); if (p.getCurrentToken() == JsonToken.FIELD_NAME) { p.nextToken(); } return new ReferenceEntry.Base(parent, reference, p.getText()); } }); mapper.registerModule(module); JsonNode data = mapper.createArrayNode() .add(mapper.createObjectNode().put("@id", "1").put("name", "Paul").put("uniqueFriend", "2")) .add(mapper.createObjectNode().put("@id", "2").put("name", "Franck")); Resource resource = mapper.reader().withAttribute(RESOURCE_SET, resourceSet) .withAttribute(ROOT_ELEMENT, ModelPackage.Literals.USER).treeToValue(data, Resource.class); assertEquals(2, resource.getContents().size()); User u1 = (User) resource.getContents().get(0); User u2 = (User) resource.getContents().get(1); assertSame(u2, u1.getUniqueFriend()); }
From source file:com.wealdtech.jackson.modules.MessageObjectsDeserializer.java
@Override public MessageObjects<? extends Object> deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException { // This assumes a strict JSON format of userId and hint followed by _type followed by prior and current (if they exist) jp.nextToken();/*from w ww.j av a2s . c o m*/ String fieldName = jp.getCurrentName(); if (!"userid".equals(fieldName)) { throw new IOException("Unexpected key \"" + fieldName + "\"; expected userid"); } jp.nextToken(); final Long userId = Long.parseLong(jp.getText()); final RequestHint hint; jp.nextToken(); fieldName = jp.getCurrentName(); if ("hint".equals(fieldName)) { // Hint is optional jp.nextToken(); hint = WealdMapper.getMapper().readValue(jp, RequestHint.class); jp.nextToken(); } else { hint = null; } fieldName = jp.getCurrentName(); if (!"_type".equals(fieldName)) { throw new IOException("Unexpected key \"" + fieldName + "\"; expected _type"); } jp.nextToken(); final String typeStr = jp.getText(); Class<? extends Object> objClass; try { objClass = Class.forName(typeStr); } catch (ClassNotFoundException cnfe) { LOGGER.error("MessageObjects has unknown class: \"{}\"", typeStr); throw new IOException("MessageObjects has unknown class: \"" + typeStr + "\"", cnfe); } // Now that we have the type we can deserialize the objects jp.nextToken(); fieldName = jp.getCurrentName(); Object prior = null; if ("prior".equals(fieldName)) { jp.nextToken(); prior = WealdMapper.getMapper().readValue(jp, objClass); jp.nextToken(); fieldName = jp.getCurrentName(); } Object current = null; if ("current".equals(fieldName)) { jp.nextToken(); current = WealdMapper.getMapper().readValue(jp, objClass); } // And build our return object try { return new MessageObjects<>(userId, hint, prior, current); } catch (DataError de) { LOGGER.error("Failed to instantiate MessageObjects: \"" + de.getLocalizedMessage() + "\""); throw new IOException("Failed to instantiate MessageObjects", de); } }
From source file:com.tikinou.schedulesdirect.core.jackson.deser.BooleanYNDeserializer.java
@Override public Boolean deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonToken t = jp.getCurrentToken();/*from w w w. j a v a 2 s. co m*/ if (t == JsonToken.VALUE_TRUE) { return Boolean.TRUE; } if (t == JsonToken.VALUE_FALSE) { return Boolean.FALSE; } if (t == JsonToken.VALUE_NULL) { return null; } if (t == JsonToken.VALUE_NUMBER_INT) { return (jp.getIntValue() != 0); } if (t == JsonToken.VALUE_STRING) { String text = jp.getText().trim(); if ("true".equals(text)) { return Boolean.TRUE; } if ("false".equals(text) || text.length() == 0) { return Boolean.FALSE; } if ("N".equalsIgnoreCase(text) || text.length() == 0) { return Boolean.FALSE; } if ("Y".equalsIgnoreCase(text)) { return Boolean.TRUE; } throw ctxt.weirdStringException(text, Boolean.class, "only \"true\" or \"false\" recognized"); } // Otherwise, no can do: throw ctxt.mappingException(Boolean.class); }
From source file:com.sdl.odata.renderer.json.writer.JsonPropertyWriterTest.java
private List<Object> getJsonArray(JsonParser jsonParser) throws IOException { List<Object> objects = new ArrayList<>(); while (jsonParser.nextToken() != JsonToken.END_ARRAY) { if (jsonParser.getCurrentToken() == JsonToken.START_OBJECT) { Map<String, String> jsonObject = getJsonObject(jsonParser); objects.add(jsonObject);//from w ww .j av a 2s . co m } else { objects.add(jsonParser.getText()); } } return objects; }
From source file:org.apache.lucene.server.handlers.BulkAddDocumentsHandler.java
@Override public String handleStreamed(Reader reader, Map<String, List<String>> params) throws Exception { JsonFactory jfactory = new JsonFactory(); JsonParser parser = jfactory.createJsonParser(reader); if (parser.nextToken() != JsonToken.START_OBJECT) { throw new IllegalArgumentException("expected JSON object"); }//from w w w .ja v a 2 s . c om if (parser.nextToken() != JsonToken.FIELD_NAME) { throw new IllegalArgumentException("expected indexName first"); } if (!parser.getText().equals("indexName")) { throw new IllegalArgumentException("expected indexName first"); } if (parser.nextToken() != JsonToken.VALUE_STRING) { throw new IllegalArgumentException("indexName should be string"); } IndexState indexState = globalState.get(parser.getText()); indexState.verifyStarted(null); if (parser.nextToken() != JsonToken.FIELD_NAME) { throw new IllegalArgumentException("expected documents next"); } if (!parser.getText().equals("documents")) { throw new IllegalArgumentException("expected documents after indexName"); } ShardState shardState = indexState.getShard(0); if (parser.nextToken() != JsonToken.START_ARRAY) { throw new IllegalArgumentException("documents should be a list"); } int count = 0; IndexingContext ctx = new IndexingContext(); AddDocumentHandler addDocHandler = (AddDocumentHandler) globalState.getHandler("addDocument"); // Parse as many doc blocks as there are: while (true) { List<Document> children = null; Document parent = null; JsonToken token = parser.nextToken(); if (token == JsonToken.END_ARRAY) { break; } if (token != JsonToken.START_OBJECT) { throw new IllegalArgumentException("expected object"); } // Parse parent + children for this one doc block: while (true) { token = parser.nextToken(); if (token == JsonToken.END_OBJECT) { // Done with parent + child in this block break; } if (token != JsonToken.FIELD_NAME) { throw new IllegalArgumentException("missing field name: " + token); } String f = parser.getText(); if (f.equals("children")) { token = parser.nextToken(); if (token != JsonToken.START_ARRAY) { throw new IllegalArgumentException("expected array for children"); } children = new ArrayList<Document>(); // Parse each child: while (true) { Document doc = addDocHandler.parseDocument(indexState, parser); if (doc == null) { break; } children.add(doc); } } else if (f.equals("parent")) { parent = addDocHandler.parseDocument(indexState, parser); } else { throw new IllegalArgumentException("unrecognized field name \"" + f + "\""); } } if (parent == null) { throw new IllegalArgumentException("missing parent"); } if (children == null) { throw new IllegalArgumentException("missing children"); } // Parent is last: children.add(parent); globalState.submitIndexingTask(shardState.getAddDocumentsJob(count, null, children, ctx)); count++; } // nocommit this is ... lameish: while (true) { if (ctx.addCount.get() == count) { break; } Thread.sleep(1); } Throwable t = ctx.getError(); if (t != null) { IOUtils.reThrow(t); } JSONObject o = new JSONObject(); o.put("indexGen", shardState.writer.getMaxCompletedSequenceNumber()); o.put("indexedDocumentBlockCount", count); return o.toString(); }