Example usage for com.google.gson.stream JsonReader beginObject

List of usage examples for com.google.gson.stream JsonReader beginObject

Introduction

In this page you can find the example usage for com.google.gson.stream JsonReader beginObject.

Prototype

public void beginObject() throws IOException 

Source Link

Document

Consumes the next token from the JSON stream and asserts that it is the beginning of a new object.

Usage

From source file:org.mitre.util.JsonUtils.java

License:Apache License

public static Map readMap(JsonReader reader) throws IOException {
    Map map = new HashMap<>();
    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        Object value = null;/*from w  w w  .  j ava 2 s .c o m*/
        switch (reader.peek()) {
        case STRING:
            value = reader.nextString();
            break;
        case BOOLEAN:
            value = reader.nextBoolean();
            break;
        case NUMBER:
            value = reader.nextLong();
            break;
        default:
            logger.debug("Found unexpected entry");
            reader.skipValue();
            continue;
        }
        map.put(name, value);
    }
    reader.endObject();
    return map;
}

From source file:org.mule.runtime.extension.internal.persistence.ModelPropertyMapTypeAdapter.java

License:Open Source License

@Override
public HierarchyClassMap<ModelProperty> read(JsonReader in) throws IOException {
    final HierarchyClassMap<ModelProperty> modelPropertyHashMap = new HierarchyClassMap<>();

    in.beginObject();
    while (in.hasNext()) {

        final Class<? extends ModelProperty> type = getClassForModelProperty(in.nextName());
        final TypeAdapter<?> adapter = gson.getAdapter(type);
        final ModelProperty read = (ModelProperty) adapter.read(in);
        modelPropertyHashMap.put(type, read);
    }/*from   w  w  w . j a  v  a2s. co m*/
    in.endObject();
    return modelPropertyHashMap;
}

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

License:Open Source License

/**
 * Get ProgramGuide data//from  www  . j a  v a 2s  .c  o m
 * @param start Date for start of data
 * @param end Date for end of data
 * @return ArrayList of Channels
 */
public ArrayList<Channel> GetProgramGuide(Date start, Date end) throws IOException {

    final Params params = new Params();
    params.put("StartTime", Globals.utcFormat(start)); //$NON-NLS-1$
    params.put("EndTime", Globals.utcFormat(end)); //$NON-NLS-1$
    params.put("StartChanId", 0); //$NON-NLS-1$
    params.put("NumChannels", -1); //$NON-NLS-1$
    params.put("Details", "true"); //$NON-NLS-1$ //$NON-NLS-2$

    InputStream is = jc.GetStream("GetProgramGuide", params); //$NON-NLS-1$
    JsonReader jreader = new JsonReader(new BufferedReader(new InputStreamReader(is, "UTF-8")) //$NON-NLS-1$
    );

    ArrayList<Channel> channels = new ArrayList<Channel>();

    jreader.beginObject();
    skipTo(jreader, JsonToken.BEGIN_OBJECT);
    jreader.beginObject();
    skipTo(jreader, JsonToken.NAME);
    while (jreader.hasNext()) {
        String name = jreader.nextName();
        if (name.equals("NumOfChannels")) { //$NON-NLS-1$
            channels.ensureCapacity(jreader.nextInt());
            break;
        }
        jreader.skipValue();
    }
    skipTo(jreader, JsonToken.BEGIN_ARRAY);
    jreader.beginArray();
    while (jreader.hasNext()) {
        jreader.beginObject();
        channels.add((Channel) gson.fromJson(jreader, Channel.class));
        jreader.endObject();
    }
    jreader.endArray();
    jreader.endObject();
    jreader.endObject();
    jreader.close();
    jc.endStream();

    return channels;

}

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   ww w .j  a va2 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.netscan.core.json.CredentialJsonAdapter.java

License:Open Source License

@Override
public Credential read(JsonReader in) throws IOException {
    in.beginObject();
    in.nextName();//from   w  w w .j  a  v  a2s  . c  o  m
    String[] str = in.nextString().split(":");
    in.endObject();
    //fixme personalize add on credential list to avoid problematic credential config.
    return new Credential(str[0], str[1], str[2]);
}

From source file:org.netscan.core.json.FilterJsonAdapter.java

License:Open Source License

@Override
public Filter read(JsonReader in) throws IOException {
    in.beginObject();
    in.nextName();/*  www.  j  a va2s .  co m*/
    String[] filter = in.nextString().replaceAll("\\s*", "").split(",");
    in.endObject();

    return new Filter(Stream.of(filter).collect(Collectors.toList()));
}

From source file:org.netscan.core.json.IPv4JsonAdapter.java

License:Open Source License

@Override
public IPv4 read(JsonReader in) throws IOException {
    in.beginObject();
    in.nextName();//from www.j ava2 s .  c  om
    String ip = in.nextString();
    in.endObject();
    return new IPv4(ip);
}

From source file:org.objectpocket.gson.CustomTypeAdapterFactory.java

License:Apache License

@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {

    TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);

    // @Entity// w  w w  .  ja  va  2  s.  c o m
    if (type.getRawType().getAnnotation(Entity.class) != null) {
        return new TypeAdapter<T>() {

            // SERIALIZE
            public void write(JsonWriter out, T obj) throws IOException {
                if (obj != null) {
                    String id = objectPocket.getIdForObject(obj);
                    // normalize
                    if (!objectPocket.isSerializeAsRoot(obj)) {
                        gson.toJson(new ProxyOut(obj.getClass().getTypeName(), id), ProxyOut.class, out);
                        return;
                    } else {
                        objectPocket.setSerializeAsRoot(obj, false);
                    }
                }
                // default serialization
                delegate.write(out, obj);
            };

            // DESERIALIZE
            @SuppressWarnings("unchecked")
            @Override
            public T read(JsonReader in) throws IOException {
                if (in.getPath().length() > 2) {
                    in.beginObject();
                    in.nextName();
                    StringBuilder sb = new StringBuilder(in.nextString());
                    String id = sb.substring(0, sb.indexOf("@"));
                    in.endObject();
                    T obj = null;
                    try {
                        obj = (T) ReflectionUtil.instantiateDefaultConstructor(type.getRawType());
                    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException
                            | NoSuchMethodException | InvocationTargetException e) {
                        throw new IOException("Could not instantiate class " + type.getRawType().getName()
                                + "\n" + "Might be that the class has no default constructor!", e);
                    }
                    objectPocket.addIdFromReadObject(obj, id);
                    return obj;
                } else {
                    T obj = delegate.read(in);
                    return obj;
                }
            }
        };
    }
    // All other
    else {
        return delegate;
    }
}

From source file:org.ohmage.OhmageApi.java

License:Apache License

private Response parseStreamingReadResponse(String url, HttpResponse response,
        StreamingResponseListener listener) {
    Result result = Result.HTTP_ERROR;
    String[] errorCodes = null;//  w  w  w .j av a  2s  . com

    // the response object that will be returned; its type is decided by outputType
    // it's also populated by a call to populateFromJSON() which transforms the server response into the Response object
    Response candidate = new Response();
    CountingInputStream inputstream = null;

    if (response != null) {
        Log.v(TAG, response.getStatusLine().toString());
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity responseEntity = response.getEntity();

            if (responseEntity != null) {
                try {

                    JsonParser parser = new JsonParser();
                    JsonReader reader = new JsonReader(new InputStreamReader(
                            new CountingInputStream(responseEntity.getContent()), "UTF-8"));
                    reader.beginObject();

                    // expecting: {result: "<status>", data: [{},{},{}...]}
                    while (reader.hasNext()) {
                        String name = reader.nextName();
                        if ("result".equals(name)) {
                            if (reader.nextString().equalsIgnoreCase("success")) {
                                result = Result.SUCCESS;
                            } else {
                                result = Result.FAILURE;
                            }
                        } else if ("data".equals(name)) {
                            reader.beginArray();

                            // do pre-read init
                            listener.beforeRead();

                            while (reader.hasNext()) {
                                JsonElement elem = parser.parse(reader);
                                listener.readObject(elem.getAsJsonObject());
                            }

                            // do post-read cleanup
                            listener.afterRead();

                            reader.endArray();
                        } else if ("errors".equals(name)) {
                            reader.beginArray();

                            List<String> errorList = new ArrayList<String>();

                            while (reader.hasNext()) {
                                // read off each of the errors and stick it
                                // into the error array
                                JsonElement elem = parser.parse(reader);
                                errorList.add(elem.getAsJsonObject().get("code").getAsString());
                            }

                            errorCodes = errorList.toArray(new String[errorList.size()]);

                            reader.endArray();
                        } else {
                            reader.skipValue();
                        }
                    }

                    reader.endObject();

                    // and we're done!
                } catch (IOException e) {
                    Log.e(TAG, "Problem reading response body", e);
                    result = Result.INTERNAL_ERROR;
                }

                try {
                    responseEntity.consumeContent();
                } catch (IOException e) {
                    Log.e(TAG, "Error consuming content", e);
                }

            } else {
                Log.e(TAG, "No response entity in response");
                result = Result.HTTP_ERROR;
            }
        } else {
            Log.e(TAG, "Returned status code: " + String.valueOf(response.getStatusLine().getStatusCode()));
            result = Result.HTTP_ERROR;
        }

    } else {
        Log.e(TAG, "Response is null");
        result = Result.HTTP_ERROR;
    }

    if (inputstream != null && result == Result.SUCCESS)
        Analytics.network(mContext, url, inputstream.amountRead());

    listener.readResult(result, errorCodes);
    candidate.setResponseStatus(result, errorCodes);

    return candidate;
}

From source file:org.onos.yangtools.yang.data.codec.gson.JsonParserStream.java

License:Open Source License

public void read(final JsonReader in, AbstractNodeDataWithSchema parent) throws IOException {
    switch (in.peek()) {
    case STRING://  w w w  .  j a va2 s  .  co m
    case NUMBER:
        setValue(parent, in.nextString());
        break;
    case BOOLEAN:
        setValue(parent, Boolean.toString(in.nextBoolean()));
        break;
    case NULL:
        in.nextNull();
        setValue(parent, null);
        break;
    case BEGIN_ARRAY:
        in.beginArray();
        while (in.hasNext()) {
            if (parent instanceof LeafNodeDataWithSchema) {
                read(in, parent);
            } else {
                final AbstractNodeDataWithSchema newChild = newArrayEntry(parent);
                read(in, newChild);
            }
        }
        in.endArray();
        return;
    case BEGIN_OBJECT:
        final Set<String> namesakes = new HashSet<>();
        in.beginObject();
        /*
         * This allows parsing of incorrectly /as showcased/
         * in testconf nesting of list items - eg.
         * lists with one value are sometimes serialized
         * without wrapping array.
         *
         */
        if (isArray(parent)) {
            parent = newArrayEntry(parent);
        }
        while (in.hasNext()) {
            final String jsonElementName = in.nextName();
            final NamespaceAndName namespaceAndName = resolveNamespace(jsonElementName, parent.getSchema());
            final String localName = namespaceAndName.getName();
            addNamespace(namespaceAndName.getUri());
            if (namesakes.contains(jsonElementName)) {
                throw new JsonSyntaxException("Duplicate name " + jsonElementName + " in JSON input.");
            }
            namesakes.add(jsonElementName);
            final Deque<DataSchemaNode> childDataSchemaNodes = findSchemaNodeByNameAndNamespace(
                    parent.getSchema(), localName, getCurrentNamespace());
            if (childDataSchemaNodes.isEmpty()) {
                throw new IllegalStateException("Schema for node with name " + localName + " and namespace "
                        + getCurrentNamespace() + " doesn't exist.");
            }

            final AbstractNodeDataWithSchema newChild = ((CompositeNodeDataWithSchema) parent)
                    .addChild(childDataSchemaNodes);
            /*
             * FIXME:anyxml data shouldn't be skipped but should be loaded somehow.
             * will be able to load anyxml which conforms to YANG data using these
             * parser, for other anyxml will be harder.
             */
            if (newChild instanceof AnyXmlNodeDataWithSchema) {
                in.skipValue();
            } else {
                read(in, newChild);
            }
            removeNamespace();
        }
        in.endObject();
        return;
    case END_DOCUMENT:
    case NAME:
    case END_OBJECT:
    case END_ARRAY:
        break;
    }
}