List of usage examples for com.fasterxml.jackson.databind JsonNode elements
public Iterator<JsonNode> elements()
From source file:com.msopentech.odatajclient.engine.data.impl.JSONDOMTreeUtils.java
/** * Recursively builds DOM content out of JSON subtree rooted at given node. * * @param client OData client./*from www. j a va2s . c o m*/ * @param document root of the DOM document being built * @param parent parent of the nodes being generated during this step * @param node JSON node to be used as source for DOM elements */ public static void buildSubtree(final ODataClient client, final Element parent, final JsonNode node) { final Iterator<String> fieldNameItor = node.fieldNames(); final Iterator<JsonNode> nodeItor = node.elements(); while (nodeItor.hasNext()) { final JsonNode child = nodeItor.next(); final String name = fieldNameItor.hasNext() ? fieldNameItor.next() : ""; // no name? array item if (name.isEmpty()) { final Element element = parent.getOwnerDocument().createElementNS( client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_DATASERVICES), ODataConstants.PREFIX_DATASERVICES + ODataConstants.ELEM_ELEMENT); parent.appendChild(element); if (child.isValueNode()) { if (child.isNull()) { element.setAttributeNS( client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA), ODataConstants.ATTR_NULL, Boolean.toString(true)); } else { element.appendChild(parent.getOwnerDocument().createTextNode(child.asText())); } } if (child.isContainerNode()) { buildSubtree(client, element, child); } } else if (!name.contains("@") && !ODataConstants.JSON_TYPE.equals(name)) { final Element property = parent.getOwnerDocument().createElementNS( client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_DATASERVICES), ODataConstants.PREFIX_DATASERVICES + name); parent.appendChild(property); boolean typeSet = false; if (node.hasNonNull(name + "@" + ODataConstants.JSON_TYPE)) { property.setAttributeNS( client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA), ODataConstants.ATTR_M_TYPE, node.get(name + "@" + ODataConstants.JSON_TYPE).textValue()); typeSet = true; } if (child.isNull()) { property.setAttributeNS( client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA), ODataConstants.ATTR_NULL, Boolean.toString(true)); } else if (child.isValueNode()) { if (!typeSet) { if (child.isInt()) { property.setAttributeNS( client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA), ODataConstants.ATTR_M_TYPE, EdmSimpleType.Int32.toString()); } if (child.isLong()) { property.setAttributeNS( client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA), ODataConstants.ATTR_M_TYPE, EdmSimpleType.Int64.toString()); } if (child.isBigDecimal()) { property.setAttributeNS( client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA), ODataConstants.ATTR_M_TYPE, EdmSimpleType.Decimal.toString()); } if (child.isDouble()) { property.setAttributeNS( client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA), ODataConstants.ATTR_M_TYPE, EdmSimpleType.Double.toString()); } if (child.isBoolean()) { property.setAttributeNS( client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA), ODataConstants.ATTR_M_TYPE, EdmSimpleType.Boolean.toString()); } if (child.isTextual()) { property.setAttributeNS( client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA), ODataConstants.ATTR_M_TYPE, EdmSimpleType.String.toString()); } } property.appendChild(parent.getOwnerDocument().createTextNode(child.asText())); } else if (child.isContainerNode()) { if (!typeSet && child.hasNonNull(ODataConstants.JSON_TYPE)) { property.setAttributeNS( client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA), ODataConstants.ATTR_M_TYPE, child.get(ODataConstants.JSON_TYPE).textValue()); } final String type = property.getAttribute(ODataConstants.ATTR_M_TYPE); if (StringUtils.isNotBlank(type) && EdmSimpleType.isGeospatial(type)) { if (EdmSimpleType.Geography.toString().equals(type) || EdmSimpleType.Geometry.toString().equals(type)) { final String geoType = child.get(ODataConstants.ATTR_TYPE).textValue(); property.setAttributeNS( client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA), ODataConstants.ATTR_M_TYPE, geoType.startsWith("Geo") ? EdmSimpleType.namespace() + "." + geoType : type + geoType); } if (child.has(ODataConstants.JSON_COORDINATES) || child.has(ODataConstants.JSON_GEOMETRIES)) { GeospatialJSONHandler.deserialize(child, property, property.getAttribute(ODataConstants.ATTR_M_TYPE)); } } else { buildSubtree(client, property, child); } } } } }
From source file:nl.esciencecenter.xnatclient.data.XnatParser.java
/** * Xnat Rest Query has a diferrent Json Tree. Parse structure * /* ww w.j a v a 2s . co m*/ * @throws XnatParseException */ public static int parseJsonQueryResult(XnatObjectType type, String jsonStr, List list) throws XnatParseException { if (StringUtil.isEmpty(jsonStr)) return 0; try { JsonFactory jsonFac = new JsonFactory(); ObjectMapper mapper = new ObjectMapper(); // use dom like parsing: JsonNode tree = mapper.readTree(jsonStr); JsonNode items = tree.get("items"); if (items == null) { logger.warnPrintf("Couldn't find 'items' in jsonTree\n"); return 0; } // parse objects: JsonNode node = null; Iterator<JsonNode> els = items.elements(); int index = 0; while (els.hasNext()) { logger.debugPrintf(" - item[%d]\n", index++); JsonNode el = els.next(); node = el.get("data_fields"); if (node != null) list.add(parseXnatObject(type, node)); else logger.warnPrintf("jsonNode doesn't have 'data_fields' element:%s", el); } } // wrap exception: catch (JsonParseException e) { throw new XnatParseException("JsonParseException:" + e.getMessage(), e); } catch (IOException e) { throw new XnatParseException("IOException:" + e.getMessage(), e); } return list.size(); }
From source file:com.gsma.mobileconnect.utils.AndroidJsonUtils.java
/** * Extract the requested URL from the Operator Not Identified Discovery response. * * @param jsonDoc The json object to check. * @param relToFind The URL to find.//from w w w .j a v a 2 s.c om * @return The requested URL if present, null otherwise. */ public static String extractUrl(JsonNode jsonDoc, String relToFind) { if (null == jsonDoc) { throw new IllegalArgumentException("Missing argument jsonDoc"); } if (null == relToFind) { throw new IllegalArgumentException("Missing argument relToFind"); } JsonNode linksNode = jsonDoc.get(Constants.LINKS_FIELD_NAME); if (null == linksNode) { return null; } Iterator<JsonNode> i = linksNode.elements(); while (i.hasNext()) { JsonNode node = i.next(); String rel = getOptionalStringValue(node, Constants.REL_FIELD_NAME); if (relToFind.equals(rel)) { return getOptionalStringValue(node, Constants.HREF_FIELD_NAME); } } return null; }
From source file:com.redhat.lightblue.mongo.config.MongoConfiguration.java
public static List<MongoCredential> credentialsFromJson(JsonNode node) { List<MongoCredential> list = new ArrayList<>(); try {/*from w w w.ja va2 s. c om*/ if (node instanceof ArrayNode) { for (Iterator<JsonNode> itr = node.elements(); itr.hasNext();) { list.add(credentialFromJson((ObjectNode) itr.next())); } } else if (node != null) { list.add(credentialFromJson((ObjectNode) node)); } } catch (ClassCastException e) { throw new IllegalArgumentException("Invalid credentials node:" + node); } return list; }
From source file:utils.HelomeUtil.java
/** * JsonNode Array???Long// ww w . j a v a 2 s . c om * * @param sourceNode ?JsonNode Array * @param fieldName ??? * @param isDesc true - ?? false - ?? * @return ?JsonNode */ public static JsonNode sortJsonNode(JsonNode sourceNode, final String fieldName, final boolean isDesc) { if (null == sourceNode || !sourceNode.isArray() || sourceNode.isMissingNode()) { LOGGER.error("sort json node fail."); return sourceNode; } List<JsonNode> sortedList = new LinkedList<>(); Iterator<JsonNode> iterator = sourceNode.elements(); while (iterator.hasNext()) { JsonNode element = iterator.next(); sortedList.add(element); } Collections.sort(sortedList, new Comparator<JsonNode>() { private int bigger = isDesc ? -1 : 1; private int smaller = -bigger; @Override public int compare(JsonNode o1, JsonNode o2) { long o1Key = o1.get(fieldName) == null ? 0 : o1.get(fieldName).asLong(); long o2Key = o2.get(fieldName) == null ? 0 : o2.get(fieldName).asLong(); return o1Key == o2Key ? 0 : o1Key > o2Key ? bigger : smaller; } }); ObjectNode sortedNode = Json.newObject(); ArrayNode arrayNode = sortedNode.arrayNode(); arrayNode.addAll(sortedList); return arrayNode; }
From source file:org.jboss.aerogear.io.netty.handler.codec.sockjs.util.JsonUtil.java
public static String[] decode(final String content) throws IOException { final JsonNode root = MAPPER.readTree(content); if (root.isObject()) { return new String[] { root.toString() }; }/*from w w w . j a va 2 s . co m*/ if (root.isValueNode()) { return new String[] { root.asText() }; } if (!root.isArray()) { throw new JsonMappingException("content must be a JSON Array but was : " + content); } final List<String> messages = new ArrayList<String>(); final Iterator<JsonNode> elements = root.elements(); while (elements.hasNext()) { final JsonNode field = elements.next(); if (field.isValueNode()) { messages.add(field.asText()); } else { messages.add(field.toString()); } } return messages.toArray(new String[messages.size()]); }
From source file:com.github.arnebinder.hide.swagger.params.HiderMojo.java
public static JsonNode merge(JsonNode mainNode, JsonNode updateNode) throws MojoExecutionException { if (updateNode instanceof ArrayNode) { if (!(mainNode instanceof ArrayNode)) { // error throw new MojoExecutionException( "Could not merge nodes: " + mainNode.toString() + " is not an ArrayNode."); } else {/*w w w . ja v a2 s . c o m*/ Iterator<JsonNode> updateElements = updateNode.elements(); while (updateElements.hasNext()) { JsonNode updateElement = updateElements.next(); if (updateElement.has("name") && updateElement.get("name") != null && updateElement.get("name").isTextual()) { String updateName = updateElement.get("name").asText(); JsonNode mNode = mainNode.findValue(updateName); if (mNode == null) { // add updateElement to mainNode ((ArrayNode) mainNode).add(updateElement); } merge(mNode, updateElement); } else { throw new MojoExecutionException("Could not find key \"name\" in ArrayNode update element: " + updateElement.toString()); } } } } else { Iterator<String> fieldNames = updateNode.fieldNames(); while (fieldNames.hasNext()) { String fieldName = fieldNames.next(); JsonNode jsonNode = mainNode.get(fieldName); // if field exists and is an embedded object if (jsonNode != null && jsonNode.isObject()) { merge(jsonNode, updateNode.get(fieldName)); } else { if (mainNode instanceof ObjectNode) { // Overwrite field JsonNode value = updateNode.get(fieldName); ((ObjectNode) mainNode).replace(fieldName, value); } } } } return mainNode; }
From source file:com.dnw.json.J.java
/** * Resolves an array <code>JsonNode</code>, returns a <code>com.dnw.json.L</code> object. For * each element in this array, recursively calls <code>parse(JsonNode)</code> to resolve it. * //from w ww .j ava 2s .c o m * @author manbaum * @since Oct 22, 2014 * @param node the given <code>JsonNode</code>. * @return a <code>com.dnw.json.L</code> object. */ private final static L resolveArray(JsonNode node) { L l = L.l(); Iterator<JsonNode> i = node.elements(); while (i.hasNext()) { l.a(resolve(i.next())); } return l; }
From source file:controllers.nwbib.Lobid.java
private static void mapIsilsToUris(JsonNode items, Map<String, List<String>> result) { Iterator<JsonNode> elements = items.isArray() ? items.elements() : Arrays.asList(items).iterator(); while (elements.hasNext()) { String itemUri = elements.next().asText(); try {//from w w w .j ava 2 s . c om String isil = itemUri.split(":")[2]; List<String> uris = result.getOrDefault(isil, new ArrayList<>()); uris.add(itemUri); result.put(isil, uris); } catch (ArrayIndexOutOfBoundsException x) { Logger.error(x.getMessage()); } } }
From source file:com.gsma.mobileconnect.utils.AndroidJsonUtils.java
/** * Parse an Operator Identified Discovery Result. * <p>/*from w w w .j a v a 2 s. co m*/ * If the discovery result looks like an Operator Identified result a ParsedOperatorIdentifiedDiscoveryResult is returned. * * @param jsonDoc The discovery result to examine. * @return The parsed operator discovery result or null. */ public static ParsedOperatorIdentifiedDiscoveryResult parseOperatorIdentifiedDiscoveryResult(JsonNode jsonDoc) { if (null == jsonDoc) { throw new IllegalArgumentException("Missing parameter jsonDoc"); } try { ParsedOperatorIdentifiedDiscoveryResult parsedOperatorIdentifiedDiscoveryResult = new ParsedOperatorIdentifiedDiscoveryResult(); JsonNode responseNode = getExpectedNode(jsonDoc, Constants.RESPONSE_FIELD_NAME); parsedOperatorIdentifiedDiscoveryResult .setClientId(getExpectedStringValue(responseNode, Constants.CLIENT_ID_FIELD_NAME)); parsedOperatorIdentifiedDiscoveryResult .setClientSecret(getExpectedStringValue(responseNode, Constants.CLIENT_SECRET_FIELD_NAME)); JsonNode linkNode = responseNode.path(Constants.APIS_FIELD_NAME).path(Constants.OPERATORID_FIELD_NAME) .path(Constants.LINK_FIELD_NAME); if (linkNode.isMissingNode()) { return null; } Iterator<JsonNode> i = linkNode.elements(); while (i.hasNext()) { JsonNode node = i.next(); String rel = getExpectedStringValue(node, Constants.REL_FIELD_NAME); if (Constants.AUTHORIZATION_REL.equals(rel)) { parsedOperatorIdentifiedDiscoveryResult .setAuthorizationHref(getExpectedStringValue(node, Constants.HREF_FIELD_NAME)); } else if (Constants.TOKEN_REL.equals(rel)) { parsedOperatorIdentifiedDiscoveryResult .setTokenHref(getExpectedStringValue(node, Constants.HREF_FIELD_NAME)); } else if (Constants.USER_INFO_REL.equals(rel)) { parsedOperatorIdentifiedDiscoveryResult .setUserInfoHref(getExpectedStringValue(node, Constants.HREF_FIELD_NAME)); } else if (Constants.PREMIUM_INFO_REL.equals(rel)) { parsedOperatorIdentifiedDiscoveryResult .setPremiumInfoHref(getExpectedStringValue(node, Constants.HREF_FIELD_NAME)); } } return parsedOperatorIdentifiedDiscoveryResult; } catch (NoFieldException ex) { return null; } }