Example usage for com.fasterxml.jackson.core JsonParser getText

List of usage examples for com.fasterxml.jackson.core JsonParser getText

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonParser getText.

Prototype

public abstract String getText() throws IOException, JsonParseException;

Source Link

Document

Method for accessing textual representation of the current token; if no current token (before first call to #nextToken , or after encountering end-of-input), returns null.

Usage

From source file:Service.java

public static void main(String[] args) {

    StringWriter sw = new StringWriter();
    try {//from   w  ww . j a  v  a2 s .c om
        JsonGenerator g = factory.createGenerator(sw);
        g.writeStartObject();
        g.writeNumberField("code", 200);
        g.writeArrayFieldStart("languages");
        for (Language l : Languages.get()) {
            g.writeStartObject();
            g.writeStringField("name", l.getName());
            g.writeStringField("locale", l.getLocaleWithCountryAndVariant().toString());
            g.writeEndObject();
        }
        g.writeEndArray();
        g.writeEndObject();
        g.flush();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    String languagesResponse = sw.toString();

    String errorResponse = codeResponse(500);
    String okResponse = codeResponse(200);

    Scanner sc = new Scanner(System.in);
    while (sc.hasNextLine()) {
        try {
            String line = sc.nextLine();
            JsonParser p = factory.createParser(line);
            String cmd = "";
            String text = "";
            String language = "";
            while (p.nextToken() != JsonToken.END_OBJECT) {
                String name = p.getCurrentName();
                if ("command".equals(name)) {
                    p.nextToken();
                    cmd = p.getText();
                }
                if ("text".equals(name)) {
                    p.nextToken();
                    text = p.getText();
                }
                if ("language".equals(name)) {
                    p.nextToken();
                    language = p.getText();
                }
            }
            p.close();

            if ("check".equals(cmd)) {
                sw = new StringWriter();
                JsonGenerator g = factory.createGenerator(sw);
                g.writeStartObject();
                g.writeNumberField("code", 200);
                g.writeArrayFieldStart("matches");
                for (RuleMatch match : new JLanguageTool(Languages.getLanguageForShortName(language))
                        .check(text)) {
                    g.writeStartObject();

                    g.writeNumberField("offset", match.getFromPos());

                    g.writeNumberField("length", match.getToPos() - match.getFromPos());

                    g.writeStringField("message", substituteSuggestion(match.getMessage()));

                    if (match.getShortMessage() != null) {
                        g.writeStringField("shortMessage", substituteSuggestion(match.getShortMessage()));
                    }

                    g.writeArrayFieldStart("replacements");
                    for (String replacement : match.getSuggestedReplacements()) {
                        g.writeString(replacement);
                    }
                    g.writeEndArray();

                    Rule rule = match.getRule();

                    g.writeStringField("ruleId", rule.getId());

                    if (rule instanceof AbstractPatternRule) {
                        String subId = ((AbstractPatternRule) rule).getSubId();
                        if (subId != null) {
                            g.writeStringField("ruleSubId", subId);
                        }
                    }

                    g.writeStringField("ruleDescription", rule.getDescription());

                    g.writeStringField("ruleIssueType", rule.getLocQualityIssueType().toString());

                    if (rule.getUrl() != null) {
                        g.writeArrayFieldStart("ruleUrls");
                        g.writeString(rule.getUrl().toString());
                        g.writeEndArray();
                    }

                    Category category = rule.getCategory();
                    CategoryId catId = category.getId();
                    if (catId != null) {
                        g.writeStringField("ruleCategoryId", catId.toString());

                        g.writeStringField("ruleCategoryName", category.getName());
                    }

                    g.writeEndObject();
                }
                g.writeEndArray();
                g.writeEndObject();
                g.flush();
                System.out.println(sw.toString());
            } else if ("languages".equals(cmd)) {
                System.out.println(languagesResponse);
            } else if ("quit".equals(cmd)) {
                System.out.println(okResponse);
                return;
            } else {
                System.out.println(errorResponse);
            }
        } catch (Exception e) {
            System.out.println(errorResponse);
        }
    }
}

From source file:org.immutables.fixture.SillyMarshalingRoutines.java

public static SillyValue unmarshal(JsonParser parser, @Nullable SillyValue enumNull,
        Class<SillyValue> expectedClass) throws IOException {
    String text = parser.getText();
    return SillyValue.valueOf(text.toUpperCase());
}

From source file:org.talend.components.jira.datum.EntityParser.java

/**
 * Parses JSON and searches for total property
 * // www . ja  va  2 s . c om
 * @param json JSON string
 * @return total property value, if it is exist or -1 otherwise
 */
static int getTotal(String json) {
    JsonFactory factory = new JsonFactory();
    try {
        JsonParser parser = factory.createParser(json);

        boolean totalFound = rewindToField(parser, "total");

        if (!totalFound) {
            return UNDEFINED;
        }

        // get total value
        String value = parser.getText();

        return Integer.parseInt(value);
    } catch (IOException e) {
        LOG.debug("Exception during JSON parsing. {}", e.getMessage());
    }
    return UNDEFINED;
}

From source file:com.github.heuermh.ensemblrestclient.JacksonSequenceConverter.java

static Sequence parseSequence(final JsonFactory jsonFactory, final InputStream inputStream) throws IOException {
    JsonParser parser = null;
    try {//w  ww  .  j a va  2s. c  om
        parser = jsonFactory.createParser(inputStream);
        parser.nextToken();

        String id = null;
        String seq = null;
        String molecule = null;

        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String field = parser.getCurrentName();
            parser.nextToken();
            if ("id".equals(field)) {
                id = parser.getText();
            } else if ("seq".equals(field)) {
                seq = parser.getText();
            } else if ("molecule".equals(field)) {
                molecule = parser.getText();
            }
        }
        return new Sequence(id, seq, molecule);
    } finally {
        try {
            inputStream.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            parser.close();
        } catch (Exception e) {
            // ignored
        }
    }
}

From source file:org.nuxeo.client.test.marshallers.DocumentMarshaller.java

protected static List<Object> readArrayProperty(JsonParser jp) throws IOException {
    List<Object> list = new ArrayList<>();
    JsonToken tok = jp.nextToken();//from  w ww  .  j a v  a2 s.c o m
    while (tok != JsonToken.END_ARRAY) {
        switch (tok) {
        case START_ARRAY:
            list.add(readArrayProperty(jp));
            break;
        case START_OBJECT:
            list.add(readObjectProperty(jp));
            break;
        default:
            list.add(jp.getText());
        }
        tok = jp.nextToken();
    }
    return list;
}

From source file:ai.susi.geo.GeoJsonReader.java

private static Map<String, String> parseMap(JsonParser parser) throws JsonParseException, IOException {
    Map<String, String> map = new HashMap<>();
    JsonToken token = parser.nextToken();
    if (!JsonToken.START_OBJECT.equals(token))
        return map;

    while (!parser.isClosed() && (token = parser.nextToken()) != null && token != JsonToken.END_OBJECT) {
        String name = parser.getCurrentName();
        token = parser.nextToken();/*ww w . j a v  a2  s  .  com*/
        String value = parser.getText();
        map.put(name.toLowerCase(), value);
    }
    return map;
}

From source file:com.google.openrtb.json.OpenRtbJsonUtils.java

/**
 * Reads from either a JSON Value String (containing CSV) or a JSON Array.
 * The dual input format is needed because some fields (e.g. keywords) were allowed
 * to be of either type in OpenRTB 2.2; now in 2.3 they are all CSV strings only.
 * TODO: Simplify this to only accept CSV strings after 2.2 compatibility is dropped.
 *///from www . ja v a 2s  .c  om
public static String readCsvString(JsonParser par) throws IOException {
    JsonToken currentToken = par.getCurrentToken();
    if (currentToken == JsonToken.START_ARRAY) {
        StringBuilder keywords = new StringBuilder();
        for (startArray(par); endArray(par); par.nextToken()) {
            if (keywords.length() != 0) {
                keywords.append(',');
            }
            keywords.append(par.getText());
        }
        return keywords.toString();
    } else if (currentToken == JsonToken.VALUE_STRING) {
        return par.getText();
    } else {
        throw new JsonParseException(par, "Expected string or array");
    }
}

From source file:org.oscim.utils.overpass.OverpassAPIReader.java

private static TagSet parseTags(JsonParser jp) throws JsonParseException, IOException {

    TagSet tags = null;//from w w w  .  jav  a2  s . co  m

    while (jp.nextToken() != JsonToken.END_OBJECT) {
        String key = jp.getCurrentName();
        jp.nextToken();
        String val = jp.getText();
        if (tags == null)
            tags = new TagSet(4);

        tags.add(new Tag(key, val, false));

    }

    return tags;
}

From source file:io.seldon.spark.actions.JobUtils.java

public static ActionData getActionDataFromActionLogLine(String actionLogLine) {
    ActionData actionData = new ActionData();

    String[] parts = actionLogLine.split("\\s+", 3);
    String json = parts[2];/*from   w  ww  .ja va  2  s. c  om*/
    actionData.timestamp_utc = parts[0];

    JsonFactory jsonF = new JsonFactory();
    try {
        JsonParser jp = jsonF.createParser(json);
        if (jp.nextToken() != JsonToken.START_OBJECT) {
            throw new IOException("Expected data to start with an Object");
        }
        while (jp.nextToken() != JsonToken.END_OBJECT) {
            String fieldName = jp.getCurrentName();
            // Let's move to value
            jp.nextToken();
            if (fieldName.equals("client")) {
                actionData.client = jp.getText();
            } else if (fieldName.equals("client_userid")) {
                actionData.client_userid = jp.getText();
            } else if (fieldName.equals("userid")) {
                actionData.userid = jp.getValueAsInt();
            } else if (fieldName.equals("itemid")) {
                actionData.itemid = jp.getValueAsInt();
            } else if (fieldName.equals("client_itemid")) {
                actionData.client_itemid = jp.getText();
            } else if (fieldName.equals("rectag")) {
                actionData.rectag = jp.getText();
            } else if (fieldName.equals("type")) {
                actionData.type = jp.getValueAsInt();
            } else if (fieldName.equals("value")) {
                actionData.value = jp.getValueAsDouble();
            }
        }
        jp.close();
    } catch (JsonParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return actionData;
}

From source file:org.nuxeo.client.test.marshallers.DocumentMarshaller.java

protected static void readProperties(JsonParser jp, Map<String, Object> props) throws IOException {
    JsonToken tok = jp.nextToken();/*from w w w  .j  ava 2 s  . co  m*/
    while (tok != null && tok != JsonToken.END_OBJECT) {
        String key = jp.getCurrentName();
        tok = jp.nextToken();
        switch (tok) {
        case START_ARRAY:
            props.put(key, readArrayProperty(jp));
            break;
        case START_OBJECT:
            props.put(key, readObjectProperty(jp));
            break;
        case VALUE_NULL:
            props.put(key, null);
            break;
        default:
            props.put(key, jp.getText());
        }
        tok = jp.nextToken();
    }
    if (tok == null) {
        throw new IllegalArgumentException("Unexpected end of stream.");
    }
}