Example usage for com.google.gson.stream JsonToken BEGIN_ARRAY

List of usage examples for com.google.gson.stream JsonToken BEGIN_ARRAY

Introduction

In this page you can find the example usage for com.google.gson.stream JsonToken BEGIN_ARRAY.

Prototype

JsonToken BEGIN_ARRAY

To view the source code for com.google.gson.stream JsonToken BEGIN_ARRAY.

Click Source Link

Document

The opening of a JSON array.

Usage

From source file:org.mythdroid.services.VideoService.java

License:Open Source License

/**
 * Get a list of videos / directories in a given subdirectory
 * @param subdir the desired subdirectory or "ROOT" for the top-level
 * @return an ArrayList of Videos/*from  w ww . j a  v  a 2  s .c om*/
 */
public ArrayList<Video> getVideos(String subdir) throws IOException {

    ArrayList<Video> videos = new ArrayList<Video>(128);

    InputStream is = jc.GetStream("GetVideoList", null); //$NON-NLS-1$

    if (is == null)
        return null;

    JsonReader jreader = new JsonReader(new BufferedReader(new InputStreamReader(is, "UTF-8")) //$NON-NLS-1$
    );

    Video vid;
    final ArrayList<String> subdirs = new ArrayList<String>(16);

    jreader.beginObject();
    skipTo(jreader, JsonToken.BEGIN_OBJECT);
    jreader.beginObject();
    skipTo(jreader, JsonToken.BEGIN_ARRAY);
    jreader.beginArray();
    while (jreader.hasNext()) {
        jreader.beginObject();
        vid = gson.fromJson(jreader, Video.class);
        jreader.endObject();

        if (!subdir.equals("ROOT") && !vid.filename.startsWith(subdir)) //$NON-NLS-1$
            continue;

        String name = vid.filename;

        if (!subdir.equals("ROOT")) //$NON-NLS-1$
            name = vid.filename.substring(subdir.length() + 1);

        int slash;
        if ((slash = name.indexOf('/')) > 0) {
            String dir = name.substring(0, slash);
            if (!subdirs.contains(dir))
                subdirs.add(dir);
        } else
            videos.add(vid);
    }
    jreader.endArray();
    jreader.endObject();
    jreader.endObject();
    jreader.close();
    jc.endStream();

    for (String name : subdirs) {
        try {
            videos.add(new Video("-1 DIRECTORY " + name)); //$NON-NLS-1$
        } catch (IllegalArgumentException e) {
            ErrUtil.logWarn(e);
        }
    }

    videos.trimToSize();

    return videos;

}

From source file:org.opendaylight.restconf.jersey.providers.JsonToPATCHBodyReader.java

License:Open Source License

/**
 * Switch value of parsed JsonToken.NAME and read edit definition or patch id
 * @param name value of token/*w w  w. j  a  va 2  s.  com*/
 * @param edit PatchEdit instance
 * @param in JsonReader reader
 * @param path InstanceIdentifierContext context
 * @param codec Draft11StringModuleInstanceIdentifierCodec codec
 * @param resultCollection collection of parsed edits
 * @throws IOException
 */
private void parseByName(@Nonnull final String name, @Nonnull final PatchEdit edit,
        @Nonnull final JsonReader in, @Nonnull final InstanceIdentifierContext path,
        @Nonnull final StringModuleInstanceIdentifierCodec codec,
        @Nonnull final List<PATCHEntity> resultCollection) throws IOException {
    switch (name) {
    case "edit":
        if (in.peek() == JsonToken.BEGIN_ARRAY) {
            in.beginArray();

            while (in.hasNext()) {
                readEditDefinition(edit, in, path, codec);
                resultCollection.add(prepareEditOperation(edit));
                edit.clear();
            }

            in.endArray();
        } else {
            readEditDefinition(edit, in, path, codec);
            resultCollection.add(prepareEditOperation(edit));
            edit.clear();
        }

        break;
    case "patch-id":
        this.patchId = in.nextString();
        break;
    default:
        break;
    }
}

From source file:org.opendaylight.restconf.jersey.providers.JsonToPATCHBodyReader.java

License:Open Source License

/**
 * Parse data defined in value node and saves it to buffer
 * @param value Buffer to read value node
 * @param in JsonReader reader//from  ww  w  .j av a 2  s . com
 * @throws IOException
 */
private void readValueNode(@Nonnull final StringBuffer value, @Nonnull final JsonReader in) throws IOException {
    in.beginObject();
    value.append("{");

    value.append("\"" + in.nextName() + "\"" + ":");

    if (in.peek() == JsonToken.BEGIN_ARRAY) {
        in.beginArray();
        value.append("[");

        while (in.hasNext()) {
            readValueObject(value, in);
            if (in.peek() != JsonToken.END_ARRAY) {
                value.append(",");
            }
        }

        in.endArray();
        value.append("]");
    } else {
        readValueObject(value, in);
    }

    in.endObject();
    value.append("}");
}

From source file:org.opendaylight.restconf.jersey.providers.JsonToPATCHBodyReader.java

License:Open Source License

/**
 * Parse one value object of data and saves it to buffer
 * @param value Buffer to read value object
 * @param in JsonReader reader/*w w w . j  a va2 s.c o  m*/
 * @throws IOException
 */
private void readValueObject(@Nonnull final StringBuffer value, @Nonnull final JsonReader in)
        throws IOException {
    in.beginObject();
    value.append("{");

    while (in.hasNext()) {
        value.append("\"" + in.nextName() + "\"");
        value.append(":");

        if (in.peek() == JsonToken.STRING) {
            value.append("\"" + in.nextString() + "\"");
        } else {
            if (in.peek() == JsonToken.BEGIN_ARRAY) {
                in.beginArray();
                value.append("[");

                while (in.hasNext()) {
                    readValueObject(value, in);
                    if (in.peek() != JsonToken.END_ARRAY) {
                        value.append(",");
                    }
                }

                in.endArray();
                value.append("]");
            } else {
                readValueObject(value, in);
            }
        }

        if (in.peek() != JsonToken.END_OBJECT) {
            value.append(",");
        }
    }

    in.endObject();
    value.append("}");
}

From source file:org.openhab.core.automation.internal.parser.gson.RuleGSONParser.java

License:Open Source License

@Override
public Set<Rule> parse(InputStreamReader reader) throws ParsingException {
    JsonReader jr = new JsonReader(reader);
    try {/*  w w w .j  av  a 2s .c o  m*/
        Set<Rule> rules = new HashSet<>();
        if (jr.hasNext()) {
            JsonToken token = jr.peek();
            if (JsonToken.BEGIN_ARRAY.equals(token)) {
                List<RuleDTO> ruleDtos = gson.fromJson(jr, new TypeToken<List<RuleDTO>>() {
                }.getType());
                for (RuleDTO ruleDto : ruleDtos) {
                    rules.add(RuleDTOMapper.map(ruleDto));
                }
            } else {
                RuleDTO ruleDto = gson.fromJson(jr, RuleDTO.class);
                rules.add(RuleDTOMapper.map(ruleDto));
            }
            return rules;
        }
    } catch (Exception e) {
        throw new ParsingException(new ParsingNestedException(ParsingNestedException.RULE, null, e));
    } finally {
        try {
            jr.close();
        } catch (IOException e) {
        }
    }
    return Collections.emptySet();
}

From source file:org.openhab.core.automation.internal.parser.gson.TemplateGSONParser.java

License:Open Source License

@Override
public Set<Template> parse(InputStreamReader reader) throws ParsingException {
    JsonReader jr = new JsonReader(reader);
    try {//from   w  w  w  . j  a v  a 2  s.  c  o  m
        if (jr.hasNext()) {
            JsonToken token = jr.peek();
            Set<Template> templates = new HashSet<>();
            if (JsonToken.BEGIN_ARRAY.equals(token)) {
                List<RuleTemplateDTO> templateDtos = gson.fromJson(jr, new TypeToken<List<RuleTemplateDTO>>() {
                }.getType());
                for (RuleTemplateDTO templateDto : templateDtos) {
                    templates.add(RuleTemplateDTOMapper.map(templateDto));
                }
            } else {
                RuleTemplateDTO template = gson.fromJson(jr, RuleTemplateDTO.class);
                templates.add(RuleTemplateDTOMapper.map(template));
            }
            return templates;
        }
    } catch (Exception e) {
        throw new ParsingException(new ParsingNestedException(ParsingNestedException.TEMPLATE, null, e));
    } finally {
        try {
            jr.close();
        } catch (IOException e) {
        }
    }
    return Collections.emptySet();
}

From source file:org.springframework.batch.item.json.GsonJsonObjectReader.java

License:Apache License

@Override
public void open(Resource resource) throws Exception {
    Assert.notNull(resource, "The resource must not be null");
    this.inputStream = resource.getInputStream();
    this.jsonReader = this.mapper.newJsonReader(new InputStreamReader(this.inputStream));
    Assert.state(this.jsonReader.peek() == JsonToken.BEGIN_ARRAY,
            "The Json input stream must start with an array of Json objects");
    this.jsonReader.beginArray();
}

From source file:org.ttrssreader.net.JSONConnector.java

License:Open Source License

private JsonReader prepareReader(Map<String, String> params, boolean firstCall) throws IOException {
    InputStream in = doRequest(params);
    if (in == null)
        return null;
    JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));

    // Check if content contains array or object, array indicates login-response or error, object is content
    try {/*from w  w  w . j  a va  2s . c o m*/
        reader.beginObject();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    while (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equals("content")) {
            JsonToken t = reader.peek();

            if (t.equals(JsonToken.BEGIN_ARRAY)) {
                return reader;
            } else if (t.equals(JsonToken.BEGIN_OBJECT)) {

                JsonObject object = new JsonObject();
                reader.beginObject();

                String nextName = reader.nextName();
                // We have a BEGIN_OBJECT here but its just the response to call "subscribeToFeed"
                if ("status".equals(nextName))
                    return reader;

                // Handle error
                while (reader.hasNext()) {
                    if (nextName != null) {
                        object.addProperty(nextName, reader.nextString());
                        nextName = null;
                    } else {
                        object.addProperty(reader.nextName(), reader.nextString());
                    }
                }
                reader.endObject();

                if (object.get(ERROR) != null) {
                    String message = object.get(ERROR).toString();

                    if (message.contains(NOT_LOGGED_IN)) {
                        lastError = NOT_LOGGED_IN;
                        if (firstCall && login() && !hasLastError)
                            return prepareReader(params, false); // Just do the same request again
                        else
                            return null;
                    }

                    if (message.contains(API_DISABLED)) {
                        hasLastError = true;
                        lastError = MyApplication.context().getString(R.string.Error_ApiDisabled,
                                Controller.getInstance().username());
                        return null;
                    }

                    // Any other error
                    hasLastError = true;
                    lastError = message;
                }
            }

        } else {
            reader.skipValue();
        }
    }
    return null;
}

From source file:org.ttrssreader.net.JSONConnector.java

License:Open Source License

private Set<Label> parseLabels(final JsonReader reader) throws IOException {
    Set<Label> ret = new HashSet<>();

    if (reader.peek().equals(JsonToken.BEGIN_ARRAY)) {
        reader.beginArray();/*from ww  w.  ja v a2 s  .  c  o  m*/
    } else {
        reader.skipValue();
        return ret;
    }

    try {
        while (reader.hasNext()) {

            Label label = new Label();
            reader.beginArray();
            try {
                label.id = Integer.parseInt(reader.nextString());
                label.caption = reader.nextString();
                label.foregroundColor = reader.nextString();
                label.backgroundColor = reader.nextString();
                label.checked = true;
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
                reader.skipValue();
                continue;
            }
            ret.add(label);
            reader.endArray();
        }
        reader.endArray();
    } catch (Exception e) {
        // Ignore exceptions here
        try {
            if (reader.peek().equals(JsonToken.END_ARRAY))
                reader.endArray();
        } catch (Exception ee) {
            // Empty!
        }
    }

    return ret;
}

From source file:org.wso2.carbon.governance.rest.api.internal.JSONMessageBodyReader.java

License:Open Source License

/**
 * Traverses through a json object and maps the keys and values to a {@link Map}
 *
 * @param reader        {@link JsonReader}
 * @param map           map that the values to be added.
 * @param token         {@link JsonToken}
 * @param isArray       whether the object is inside a json array
 * @throws IOException  If unable to parse the json object
 *//*from  w ww  .jav a  2 s.c  o  m*/
protected void handleObject(JsonReader reader, Map<String, Object> map, JsonToken token, boolean isArray)
        throws IOException {
    String key = null;
    while (true) {
        if (token == null) {
            token = reader.peek();
        }

        if (JsonToken.BEGIN_OBJECT.equals(token)) {
            reader.beginObject();

        } else if (JsonToken.END_OBJECT.equals(token)) {
            reader.endObject();

        } else if (JsonToken.NAME.equals(token)) {
            key = reader.nextName();

        } else if (JsonToken.STRING.equals(token)) {
            String value = reader.nextString();
            handleValue(key, value, map, isArray);
            key = null;

        } else if (JsonToken.NUMBER.equals(token)) {
            Double value = reader.nextDouble();
            handleValue(key, value, map, isArray);
            key = null;

        } else if (token.equals(JsonToken.BEGIN_ARRAY)) {
            Map<String, Object> values = handleArray(reader);
            if (key != null) {
                map.put(key, values);
            }

        } else {
            reader.skipValue();
        }

        if (reader.hasNext()) {
            token = reader.peek();
        } else {
            break;
        }
    }
}