Example usage for com.fasterxml.jackson.databind JsonNode get

List of usage examples for com.fasterxml.jackson.databind JsonNode get

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind JsonNode get.

Prototype

public JsonNode get(String paramString) 

Source Link

Usage

From source file:com.attribyte.essem.util.Util.java

/**
 * Gets an long value from a node./*ww  w. j  a  v  a 2  s  .  c o  m*/
 * @param node The parent node.
 * @param key The key.
 * @param defaultValue The default value.
 * @return The value or default value.
 */
public static long getLongField(final JsonNode node, final String key, final long defaultValue) {
    JsonNode field = node.get(key);
    if (field != null && field.canConvertToInt()) {
        return field.longValue();
    } else {
        return defaultValue;
    }
}

From source file:com.attribyte.essem.util.Util.java

/**
 * Gets a double value from a node.//from w ww .j  a  va 2s .co m
 * @param node The parent node.
 * @param key The key.
 * @param defaultValue The default value.
 * @return The value or default value.
 */
public static double getDoubleField(final JsonNode node, final String key, final double defaultValue) {
    JsonNode field = node.get(key);
    if (field != null && field.isNumber()) {
        return field.doubleValue();
    } else {
        return defaultValue;
    }
}

From source file:com.twosigma.beaker.table.serializer.TableDisplayDeSerializer.java

public static Pair<String, Object> getDeserializeObject(BeakerObjectConverter parent, JsonNode n,
        ObjectMapper mapper) {// www . j  a va 2 s .  com
    Object o = null;
    String subtype = null;
    try {
        List<List<?>> values = TableDisplayDeSerializer.getValues(parent, n, mapper);
        List<String> columns = TableDisplayDeSerializer.getColumns(n, mapper);
        List<String> classes = TableDisplayDeSerializer.getClasses(n, mapper);

        if (n.has("subtype"))
            subtype = mapper.readValue(n.get("subtype").asText(), String.class);

        if (subtype != null && subtype.equals(TableDisplay.DICTIONARY_SUBTYPE)) {
            o = getValuesAsDictionary(parent, n, mapper);
        } else if (subtype != null && subtype.equals(TableDisplay.LIST_OF_MAPS_SUBTYPE) && columns != null
                && values != null) {
            o = getValuesAsRows(parent, n, mapper);
        } else if (subtype != null && subtype.equals(TableDisplay.MATRIX_SUBTYPE)) {
            o = getValuesAsMatrix(parent, n, mapper);
        }
        if (o == null) {
            if (n.has("hasIndex") && mapper.readValue(n.get("hasIndex").asText(), String.class).equals("true")
                    && columns != null && values != null) {
                columns.remove(0);
                classes.remove(0);
                for (List<?> v : values) {
                    v.remove(0);
                }
                o = new TableDisplay(values, columns, classes);
            } else {
                o = new TableDisplay(values, columns, classes);
            }
        }
    } catch (Exception e) {
        logger.error("exception deserializing TableDisplay ", e);
    }
    return new ImmutablePair<String, Object>(subtype, o);
}

From source file:com.github.fge.jsonschema2avro.predicates.AvroPredicates.java

public static Predicate<AvroPayload> isEnum() {
    return new Predicate<AvroPayload>() {
        @Override//from   w w  w  .j  ava  2  s .c o  m
        public boolean apply(final AvroPayload input) {
            final JsonNode node = schemaNode(input);
            final Set<String> set = Sets.newHashSet(node.fieldNames());
            set.retainAll(KNOWN_KEYWORDS);
            if (!set.equals(ImmutableSet.of("enum")))
                return false;

            // Test individual entries: they must be strings, and must be
            // the same "shape" as any Avro name
            for (final JsonNode element : node.get("enum")) {
                if (!element.isTextual())
                    return false;
                if (!isValidAvroName(element.textValue()))
                    return false;
            }

            return true;
        }
    };
}

From source file:models.Collection.java

public static Collection parseCollectionFromJSON(JsonNode collectionJSON) {
    /*communities list//from   w ww . j a v a 2 s  . c  o  m
    copyrightText
        countItems
    handle
        id
    introText
    items list ids
        license
    logo
        name
    provenance
        shortDescription
    sidebarText
        type
    entityReference, entityURL, entityId
      */

    Collection collection = new Collection();

    collection.id = collectionJSON.get("id").asLong();
    collection.name = collectionJSON.get("name").asText();
    collection.handle = collectionJSON.get("handle").asText();

    if (collectionJSON.has("copyrightText")) {
        collection.copyrightText = collectionJSON.get("copyrightText").asText();
    }

    if (collectionJSON.has("numberItems")) {
        collection.countItems = collectionJSON.get("numberItems").asInt();
    }

    if (collectionJSON.has("logo")) {
        JsonNode logoNode = collectionJSON.get("logo");
        if (!logoNode.isNull()) {
            collection.logo = Bitstream.parseBitstreamFromJSON(logoNode);
        }
    }

    //@TODO Is it comm.introductoryText and coll.introText ?
    List<String> introductoryText = collectionJSON.findValuesAsText("introductoryText");
    if (!introductoryText.isEmpty()) {
        collection.introText = introductoryText.get(0);
    }

    List<String> shortDescription = collectionJSON.findValuesAsText("shortDescription");
    if (!shortDescription.isEmpty()) {
        collection.shortDescription = shortDescription.get(0);
    }

    List<String> sidebarText = collectionJSON.findValuesAsText("sidebarText");
    if (!sidebarText.isEmpty()) {
        collection.sidebarText = sidebarText.get(0);
    }

    JsonNode commNodes = collectionJSON.get("parentCommunityList");
    if (commNodes != null) {
        for (JsonNode comm : commNodes) {
            Community community = Community.parseCommunityFromJSON(comm);
            collection.parentCommunities.add(community);
        }
    }

    JsonNode itemNodes = collectionJSON.get("items");
    if (itemNodes != null) {
        for (JsonNode itemNode : itemNodes) {
            Item item = Item.parseItemFromJSON(itemNode);
            collection.items.add(item);
        }
    }

    return collection;
}

From source file:de.up.ling.irtg.util.FirstOrderModel.java

/**
 * Reads the options from a Json string representation. The options for the
 * SetAlgebra consist in a specification of the universe and the
 * interpretations of the atomic concepts. For instance, the following
 * string says that "sleep" is a binary relation with the single element
 * (e,r1), whereas "rabbit" is a unary relation containing the elements r1
 * and r2.<p>//from w  w  w . j  a v  a 2s  . com
 *
 * {"sleep": [["e", "r1"]], "rabbit": [["r1"], ["r2"]], "white": [["r1"],
 * ["b"]], "in": [["r1","h"], ["f","h2"]], "hat": [["h"], ["h2"]] }
 *
 *
 * @param optionReader
 * @throws Exception
 */
public static FirstOrderModel read(Reader optionReader) throws Exception {
    FirstOrderModel model = new FirstOrderModel();

    String optionString = StringTools.slurp(optionReader);
    Map<String, Set<List<String>>> atomicInterpretations = new HashMap<String, Set<List<String>>>();

    if (!optionString.trim().equals("")) {

        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = mapper.readValue(optionString, JsonNode.class);

        if (!root.isObject()) {
            throw new Exception("Invalid universe description: should be a map");
        } else {
            Iterator<String> preds = root.fieldNames();

            while (preds.hasNext()) {
                String pred = preds.next();
                Set<List<String>> tuples = new HashSet<List<String>>();
                JsonNode child = root.get(pred);

                if (!child.isArray()) {
                    throw new Exception("Invalid universe description: Entry '" + pred + "' should be a list.");
                } else {
                    int childIndex = 0;
                    for (JsonNode tuple : child) {
                        List<String> tupleElements = new ArrayList<String>();
                        childIndex++;

                        if (!tuple.isArray()) {
                            throw new Exception("Invalid universe description: tuple " + childIndex + " under '"
                                    + pred + "' should be a list.");
                        } else {
                            for (JsonNode tupleEl : tuple) {
                                tupleElements.add(tupleEl.textValue());
                            }
                        }

                        tuples.add(tupleElements);
                    }
                }

                atomicInterpretations.put(pred, tuples);
            }
        }
    }

    model.setAtomicInterpretations(atomicInterpretations);
    return model;
}

From source file:org.dd4t.databind.builder.json.JsonModelConverter.java

private static void handleEmbeddedContent(final JsonNode currentField, final List<JsonNode> nodeList) {
    final JsonNode embeddedNode = currentField.get(DataBindConstants.EMBEDDED_VALUES_NODE);
    // This is a fix for when we are already in an embedded node. The Json unfortunately
    // keeps sibling nodes in this child, which has FieldType embedded, while we're actually already in
    // that node's Values

    final JsonNode schemaNode = currentField.get(DataBindConstants.EMBEDDED_SCHEMA_FIELD_NAME);
    if (embeddedNode != null) {
        final Iterator<JsonNode> embeddedIterator = embeddedNode.elements();
        while (embeddedIterator.hasNext()) {
            addEmbeddedNodeAndSchemaInfo(nodeList, schemaNode, embeddedIterator);
        }/*  w  w w  .j av a 2s  . c om*/
    } else {
        final Iterator<JsonNode> currentFieldElements = currentField.elements();
        while (currentFieldElements.hasNext()) {

            addEmbeddedNodeAndSchemaInfo(nodeList, schemaNode, currentFieldElements);
        }
    }
}

From source file:com.meetingninja.csse.database.MeetingDatabaseAdapter.java

public static Meeting createMeeting(String userID, Meeting m) throws IOException, MalformedURLException {
    // Server URL setup
    String _url = getBaseUri().appendPath(userID).build().toString();

    // establish connection
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.setRequestMethod("POST");
    addRequestHeader(conn, true);/*from  w w w  .  j  a  va2 s.c om*/

    // prepare POST payload
    ByteArrayOutputStream json = new ByteArrayOutputStream();
    // this type of print stream allows us to get a string easily
    PrintStream ps = new PrintStream(json);
    // Create a generator to build the JSON string
    JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8);

    // Build JSON Object
    jgen.writeStartObject();
    jgen.writeStringField(Keys.User.ID, userID);
    jgen.writeStringField(Keys.Meeting.TITLE, m.getTitle());
    jgen.writeStringField(Keys.Meeting.LOCATION, m.getLocation());
    jgen.writeStringField(Keys.Meeting.DATETIME, m.getStartTime());
    jgen.writeStringField(Keys.Meeting.OTHEREND, m.getEndTime());
    jgen.writeStringField(Keys.Meeting.DESC, m.getDescription());
    jgen.writeArrayFieldStart(Keys.Meeting.ATTEND);
    // TODO: Add attendees to meeting
    // for (String attendee : m.getAttendance()) {
    // if (attendee.isAttending()) {
    jgen.writeStartObject();
    jgen.writeStringField(Keys.User.ID, userID);
    jgen.writeEndObject();
    // }
    // }
    jgen.writeEndArray();
    jgen.writeEndObject();
    jgen.close();

    // Get JSON Object payload from print stream
    String payload = json.toString("UTF8");
    ps.close();

    // send payload
    int responseCode = sendPostPayload(conn, payload);
    String response = getServerResponse(conn);

    // prepare to get the id of the created Meeting
    JsonNode responseMap;
    m.setID(404);
    Meeting created = new Meeting(m);
    /*
     * result should get valid={"meetingID":"##"}
     */
    //      String result = new String();
    if (!response.isEmpty()) {
        responseMap = MAPPER.readTree(response);
        if (responseMap.has(Keys.Meeting.ID))
            created.setID(responseMap.get(Keys.Meeting.ID).asText());
    }

    //      if (!result.equalsIgnoreCase("invalid"))
    //         created.setID(result);

    conn.disconnect();
    return created;
}

From source file:com.msopentech.odatajclient.engine.data.json.GeospatialJSONHandler.java

public static void deserialize(final JsonNode node, final Element parent, final String type) {
    final Iterator<JsonNode> cooItor = node.has(ODataConstants.JSON_COORDINATES)
            ? node.get(ODataConstants.JSON_COORDINATES).elements()
            : Collections.<JsonNode>emptyList().iterator();

    Element root = null;/*  ww w. j a va2s .  c  o  m*/
    final EdmSimpleType edmSimpleType = EdmSimpleType.fromValue(type);
    switch (edmSimpleType) {
    case GeographyPoint:
    case GeometryPoint:
        root = deserializePoint(parent.getOwnerDocument(), cooItor);
        break;

    case GeographyMultiPoint:
    case GeometryMultiPoint:
        root = parent.getOwnerDocument().createElementNS(ODataConstants.NS_GML, ODataConstants.ELEM_MULTIPOINT);
        if (cooItor.hasNext()) {
            final Element pointMembers = parent.getOwnerDocument().createElementNS(ODataConstants.NS_GML,
                    ODataConstants.ELEM_POINTMEMBERS);
            root.appendChild(pointMembers);
            while (cooItor.hasNext()) {
                final Iterator<JsonNode> mpItor = cooItor.next().elements();
                pointMembers.appendChild(deserializePoint(parent.getOwnerDocument(), mpItor));
            }
        }
        break;

    case GeographyLineString:
    case GeometryLineString:
        root = deserializeLineString(parent.getOwnerDocument(), cooItor);
        break;

    case GeographyMultiLineString:
    case GeometryMultiLineString:
        root = parent.getOwnerDocument().createElementNS(ODataConstants.NS_GML,
                ODataConstants.ELEM_MULTILINESTRING);
        if (cooItor.hasNext()) {
            final Element lineStringMembers = parent.getOwnerDocument().createElementNS(ODataConstants.NS_GML,
                    ODataConstants.ELEM_LINESTRINGMEMBERS);
            root.appendChild(lineStringMembers);
            while (cooItor.hasNext()) {
                final Iterator<JsonNode> mlsItor = cooItor.next().elements();
                lineStringMembers.appendChild(deserializeLineString(parent.getOwnerDocument(), mlsItor));
            }
        }
        break;

    case GeographyPolygon:
    case GeometryPolygon:
        root = deserializePolygon(parent.getOwnerDocument(), cooItor);
        break;

    case GeographyMultiPolygon:
    case GeometryMultiPolygon:
        root = parent.getOwnerDocument().createElementNS(ODataConstants.NS_GML,
                ODataConstants.ELEM_MULTIPOLYGON);
        if (cooItor.hasNext()) {
            final Element surfaceMembers = parent.getOwnerDocument().createElementNS(ODataConstants.NS_GML,
                    ODataConstants.ELEM_SURFACEMEMBERS);
            root.appendChild(surfaceMembers);
            while (cooItor.hasNext()) {
                final Iterator<JsonNode> mpItor = cooItor.next().elements();
                surfaceMembers.appendChild(deserializePolygon(parent.getOwnerDocument(), mpItor));
            }
        }
        break;

    case GeographyCollection:
    case GeometryCollection:
        root = parent.getOwnerDocument().createElementNS(ODataConstants.NS_GML,
                ODataConstants.ELEM_GEOCOLLECTION);
        if (node.has(ODataConstants.JSON_GEOMETRIES)) {
            final Iterator<JsonNode> geoItor = node.get(ODataConstants.JSON_GEOMETRIES).elements();
            if (geoItor.hasNext()) {
                final Element geometryMembers = parent.getOwnerDocument().createElementNS(ODataConstants.NS_GML,
                        ODataConstants.ELEM_GEOMEMBERS);
                root.appendChild(geometryMembers);

                while (geoItor.hasNext()) {
                    final JsonNode geo = geoItor.next();
                    final String collItemType = geo.get(ODataConstants.ATTR_TYPE).asText();
                    final String callAsType;
                    if (EdmSimpleType.GeographyCollection.name().equals(collItemType)
                            || EdmSimpleType.GeometryCollection.name().equals(collItemType)) {

                        callAsType = collItemType;
                    } else {
                        callAsType = (edmSimpleType == EdmSimpleType.GeographyCollection ? "Geography"
                                : "Geometry") + collItemType;
                    }

                    deserialize(geo, geometryMembers, EdmSimpleType.namespace() + "." + callAsType);
                }
            }
        }
        break;

    default:
    }

    if (root != null) {
        parent.appendChild(root);
        if (node.has(ODataConstants.JSON_CRS)) {
            root.setAttribute(ODataConstants.ATTR_SRSNAME,
                    ODataConstants.JSON_GIS_URLPREFIX + node.get(ODataConstants.JSON_CRS)
                            .get(ODataConstants.PROPERTIES).get(ODataConstants.NAME).asText().split(":")[1]);
        }
    }
}

From source file:com.twosigma.beakerx.table.serializer.TableDisplayDeSerializer.java

public static Pair<String, Object> getDeserializeObject(BeakerObjectConverter parent, JsonNode n,
        ObjectMapper mapper) {/* w w w .ja  v a2 s.  co m*/
    Object o = null;
    String subtype = null;
    try {
        List<List<?>> values = TableDisplayDeSerializer.getValues(parent, n, mapper);
        List<String> columns = TableDisplayDeSerializer.getColumns(n, mapper);
        List<String> classes = TableDisplayDeSerializer.getClasses(n, mapper);

        if (n.has("subtype"))
            subtype = mapper.readValue(n.get("subtype").toString(), String.class);

        if (subtype != null && subtype.equals(TableDisplay.DICTIONARY_SUBTYPE)) {
            o = getValuesAsDictionary(parent, n, mapper);
        } else if (subtype != null && subtype.equals(TableDisplay.LIST_OF_MAPS_SUBTYPE) && columns != null
                && values != null) {
            o = getValuesAsRows(parent, n, mapper);
        } else if (subtype != null && subtype.equals(TableDisplay.MATRIX_SUBTYPE)) {
            o = getValuesAsMatrix(parent, n, mapper);
        }
        if (o == null) {
            if (n.has("hasIndex") && mapper.readValue(n.get("hasIndex").asText(), String.class).equals("true")
                    && columns != null && values != null && n.has(INDEX_NAME)) {
                o = handleIndex(n, mapper, values, columns, classes);
            } else {
                o = new TableDisplay(values, columns, classes);
            }

        }
    } catch (Exception e) {
        logger.error("exception deserializing TableDisplay ", e);
    }
    return new ImmutablePair<String, Object>(subtype, o);
}