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

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

Introduction

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

Prototype

public boolean hasNext() throws IOException 

Source Link

Document

Returns true if the current array or object has another element.

Usage

From source file:eu.fayder.restcountries.rest.CountryServiceBase.java

License:Mozilla Public License

protected List<? extends BaseCountry> loadJson(String filename, Class<? extends BaseCountry> clazz) {
    LOG.debug("Loading JSON " + filename);
    List<BaseCountry> countries = new ArrayList<>();
    InputStream is = CountryServiceBase.class.getClassLoader().getResourceAsStream(filename);
    Gson gson = new Gson();
    JsonReader reader;
    try {/*from   w w  w  .  j  a v  a  2  s .c om*/
        reader = new JsonReader(new InputStreamReader(is, "UTF-8"));
        reader.beginArray();
        while (reader.hasNext()) {
            BaseCountry country = gson.fromJson(reader, clazz);
            countries.add(country);
        }
    } catch (Exception e) {
        LOG.error("Could not load JSON " + filename);
    }
    return countries;
}

From source file:eu.jtzipi.project0.common.json.impl.GsonReadWrite.java

License:Apache License

static Collection<Object> parseArray(final JsonReader jsonReader) throws IOException {
    assert null != jsonReader : "DEBUG: The json Reader is null";

    Collection<Object> l = new ArrayList<>();
    JsonToken tok;/*  w  w w  .j a  v  a  2  s .  c o  m*/

    //
    while (jsonReader.hasNext()) {

        tok = jsonReader.peek();
        // we reach the end of this array
        if (JsonToken.END_ARRAY == tok) {
            jsonReader.endArray();
            // return
            break;
        }
        // what token
        switch (tok) {
        // if array/map - parse and append
        case BEGIN_ARRAY:
            l.add(parseArray(jsonReader));
            break;
        case BEGIN_OBJECT:
            l.add(parseObject(jsonReader));
            break;
        // if raw type
        case STRING:
            l.add(jsonReader.nextString());
            break;
        case BOOLEAN:
            l.add(jsonReader.nextBoolean());
            break;
        case NUMBER:
            l.add(jsonReader.nextDouble());
            break;
        // if null , add null and consume
        case NULL:
            l.add(null);
            jsonReader.nextNull();
            break;

        // all other cases are errors
        default:
            throw new IllegalStateException("Wrong Token '" + tok + "' , while parsing an array");
        }
    }

    return l;
}

From source file:eu.jtzipi.project0.common.json.impl.GsonReadWrite.java

License:Apache License

static Map<String, Object> parseObject(final JsonReader jsonReader) throws IOException {

    Map<String, Object> map = new HashMap<>();
    String tempKey;//from ww w  . ja v a2s.c  o  m
    JsonToken tok;
    //
    while (jsonReader.hasNext()) {

        // since we want to restore a map we assue a key/value pair
        tempKey = jsonReader.nextName();
        //
        tok = jsonReader.peek();
        // we reach the end of this array
        if (JsonToken.END_ARRAY == tok) {
            jsonReader.endArray();
            // return
            break;
        }
        // what token
        switch (tok) {
        // if array/map - parse and append
        case BEGIN_ARRAY:
            map.put(tempKey, parseArray(jsonReader));
            break;
        case BEGIN_OBJECT:
            map.put(tempKey, parseObject(jsonReader));
            break;
        // if raw type
        case STRING:
            map.put(tempKey, jsonReader.nextString());
            break;
        case BOOLEAN:
            map.put(tempKey, jsonReader.nextBoolean());
            break;
        case NUMBER:
            map.put(tempKey, jsonReader.nextDouble());
            break;
        // if null , add null and consume
        case NULL:
            map.put(tempKey, null);
            jsonReader.nextNull();
            break;

        // all other cases are errors
        default:
            throw new IllegalStateException("Wrong Token '" + tok + "' , while parsing an array");
        }
    }

    return map;
}

From source file:fayder.restcountries.rest.CountryServiceHelper.java

License:Mozilla Public License

public static List<? extends BaseCountry> loadJson(String filename, Class<? extends BaseCountry> clazz) {
    LOG.debug("Loading JSON " + filename);
    List<BaseCountry> countries = new ArrayList<>();
    InputStream is = CountryServiceHelper.class.getClassLoader().getResourceAsStream(filename);
    Gson gson = new Gson();
    JsonReader reader;
    try {//from   w w  w  .j a v  a 2 s  .  c o m
        reader = new JsonReader(new InputStreamReader(is, "UTF-8"));
        reader.beginArray();
        while (reader.hasNext()) {
            BaseCountry country = gson.fromJson(reader, clazz);
            countries.add(country);
        }
    } catch (Exception e) {
        LOG.error("Could not load JSON " + filename);
    }
    return countries;
}

From source file:geomesa.example.twitter.ingest.TwitterParser.java

License:Apache License

private JsonObject next(final JsonParser parser, final JsonReader reader, final String sourceName)
        throws IOException {
    while (reader.hasNext() && reader.peek() != JsonToken.END_DOCUMENT) {
        try {/*from w  w  w .  ja v  a2  s . c  om*/
            final JsonElement element = parser.parse(reader);
            if (element != null && element != JsonNull.INSTANCE) {
                return element.getAsJsonObject();
            }
        } catch (Exception e) {
            log.error(sourceName + " - error parsing json", e);
            return null;
        }
    }
    return null;
}

From source file:guru.qas.martini.report.DefaultTraceabilityMatrix.java

License:Apache License

@Override
public void createReport(JsonReader reader, OutputStream outputStream) throws IOException {
    checkNotNull(reader, "null JsonReader");
    checkNotNull(outputStream, "null OutputStream");

    Workbook workbook = new XSSFWorkbook();
    Sheet sheet = workbook.createSheet("Results");
    addHeader(sheet);//from w  w w .  j  av a2 s  .c  om

    State state = new DefaultState();
    while (reader.hasNext()) {
        JsonToken peek = reader.peek();

        JsonObject object;
        switch (peek) {
        case BEGIN_ARRAY:
            reader.beginArray();
            continue;
        case BEGIN_OBJECT:
            object = gson.fromJson(reader, JsonObject.class);
            break;
        case END_ARRAY:
            reader.endArray();
            continue;
        case END_DOCUMENT:
            reader.skipValue();
            continue;
        default:
            JsonElement element = gson.fromJson(reader, JsonElement.class);
            LOGGER.warn("skipping unhandled element {}", element);
            continue;
        }

        switch (JsonObjectType.evaluate(object)) {
        case SUITE:
            JsonObject suite = SUITE.get(object);
            state.addSuite(suite);
            break;
        case FEATURE:
            JsonObject feature = FEATURE.get(object);
            state.addFeature(feature);
            break;
        case RESULT:
            JsonObject result = RESULT.get(object);
            addResult(state, sheet, result);
            break;
        default:
            LOGGER.warn("skipping unrecognized JsonObject: {}", object);
        }
    }

    state.updateResults();
    resizeColumns(sheet);

    Sheet suiteSheet = workbook.createSheet("Suites");
    state.updateSuites(suiteSheet);

    workbook.write(outputStream);
    outputStream.flush();
}

From source file:io.bouquet.v4.GsonFactory.java

License:Apache License

@Override
public ApiException read(JsonReader in) throws IOException {
    in.beginObject();//from www  .j  av  a2s . c om
    String message = null;
    int code = 0;
    String redirectURL = null;
    String clientId = null;
    String type = null;
    while (in.hasNext()) {
        switch (in.nextName()) {
        case "code":
            code = in.nextInt();
            break;
        case "type":
            type = in.nextString();
        case "error":
            message = in.nextString();
        case "redirectURL":
            redirectURL = in.nextString();
        case "clientId":
            clientId = in.nextString();
        }
    }
    ApiException ae = new ApiException(code, message);
    ae.setType(type);
    ae.setRedirectURL(redirectURL);
    ae.setClientId(clientId);
    return ae;
}

From source file:io.github.rcarlosdasilva.weixin.core.json.adapter.OpenPlatformAuthGetLicenseInformationResponseTypeAdapter.java

@Override
public OpenPlatformAuthGetLicenseInformationResponse read(JsonReader in) throws IOException {
    OpenPlatformAuthGetLicenseInformationResponse model = new OpenPlatformAuthGetLicenseInformationResponse();

    in.beginObject();/*from  w w w . ja  v  a  2 s  .  c o  m*/
    while (in.hasNext()) {
        String key = in.nextName();
        switch (key) {
        case Convention.OPEN_PLATFORM_AUTH_LICENSED_INFORMATION_KEY:
            readLicensedAccessToken(in, model);
            break;
        case Convention.OPEN_PLATFORM_AUTH_LICENSOR_INFORMATION_KEY:
            readLicensorInformation(in, model);
            break;
        case Convention.OPEN_PLATFORM_AUTH_LICENSED_ACCESS_TOKEN_KEY:
            model.getLicensedAccessToken().setAccessToken(in.nextString());
            break;
        case Convention.OPEN_PLATFORM_AUTH_LICENSED_ACCESS_TOKEN_EXPIRES_IN_KEY:
            model.getLicensedAccessToken().setExpiresIn(in.nextInt());
            break;
        case Convention.OPEN_PLATFORM_AUTH_LICENSED_REFRESH_TOKEN_KEY:
            model.getLicensedAccessToken().setRefreshToken(in.nextString());
            break;
        default:
            if (in.hasNext()) {
                String value = in.nextString();
                logger.warn(LOG_UNKNOWN_JSON_KEY, key, value);
            }
        }
    }

    in.endObject();

    return model;
}

From source file:io.github.rcarlosdasilva.weixin.core.json.adapter.OpenPlatformAuthGetLicenseInformationResponseTypeAdapter.java

private void readLicensedAccessToken(JsonReader in, OpenPlatformAuthGetLicenseInformationResponse model)
        throws IOException {
    LicensingInformation licensingInformation = new LicensingInformation();
    in.beginObject();//from  w  ww  . j  a  v a  2s  .co  m

    while (in.hasNext()) {
        String key = in.nextName();
        switch (key) {
        case Convention.OPEN_PLATFORM_AUTH_LICENSED_APPID_ALIAS_KEY:
        case Convention.OPEN_PLATFORM_AUTH_LICENSED_APPID_KEY:
            licensingInformation.setAppId(in.nextString());
            break;
        case Convention.OPEN_PLATFORM_AUTH_LICENSED_ACCESS_TOKEN_KEY:
            model.getLicensedAccessToken().setAccessToken(in.nextString());
            break;
        case Convention.OPEN_PLATFORM_AUTH_LICENSED_ACCESS_TOKEN_EXPIRES_IN_KEY:
            model.getLicensedAccessToken().setExpiresIn(in.nextInt());
            break;
        case Convention.OPEN_PLATFORM_AUTH_LICENSED_REFRESH_TOKEN_KEY:
            model.getLicensedAccessToken().setRefreshToken(in.nextString());
            break;
        case Convention.OPEN_PLATFORM_AUTH_LICENSED_FUNCTIONS_INFO_KEY: {
            in.beginArray();

            while (in.hasNext()) {
                in.beginObject();
                in.nextName();
                in.beginObject();
                in.nextName();
                licensingInformation.addLicencedFunction(in.nextInt());
                in.endObject();
                in.endObject();
            }

            in.endArray();
            break;
        }
        default:
            if (in.hasNext()) {
                String value = in.nextString();
                logger.warn(LOG_UNKNOWN_JSON_KEY, key, value);
            }
        }
    }

    in.endObject();
    model.setLicensingInformation(licensingInformation);
}

From source file:io.github.rcarlosdasilva.weixin.core.json.adapter.OpenPlatformAuthGetLicenseInformationResponseTypeAdapter.java

private void readLicensorInformation(JsonReader in, OpenPlatformAuthGetLicenseInformationResponse model)
        throws IOException {
    LicensorInfromation licensorInfromation = new LicensorInfromation();
    in.beginObject();/*from  w  w  w.  ja va 2 s  .  c  o  m*/

    while (in.hasNext()) {
        String key = in.nextName();
        switch (key) {
        case Convention.OPEN_PLATFORM_AUTH_LICENSOR_NICKNAME_KEY:
            licensorInfromation.setNickName(in.nextString());
            break;
        case Convention.OPEN_PLATFORM_AUTH_LICENSOR_LOGO_KEY:
            licensorInfromation.setLogo(in.nextString());
            break;
        case Convention.OPEN_PLATFORM_AUTH_LICENSOR_ACCOUNT_TYPE_KEY: {
            in.beginObject();
            in.nextName();
            licensorInfromation.setAccountType(in.nextInt());
            in.endObject();
            break;
        }
        case Convention.OPEN_PLATFORM_AUTH_LICENSOR_ACCOUNT_VERIFIED_TYPE_KEY: {
            in.beginObject();
            in.nextName();
            licensorInfromation.setAccountVerifiedType(in.nextInt());
            in.endObject();
            break;
        }
        case Convention.OPEN_PLATFORM_AUTH_LICENSOR_MPID_KEY:
            licensorInfromation.setMpId(in.nextString());
            break;
        case Convention.OPEN_PLATFORM_AUTH_LICENSOR_PRINCIPAL_NAME_KEY:
            licensorInfromation.setPrincipalName(in.nextString());
            break;
        case Convention.OPEN_PLATFORM_AUTH_LICENSOR_ACCOUNT_NAME_KEY:
            licensorInfromation.setAccountName(in.nextString());
            break;
        case Convention.OPEN_PLATFORM_AUTH_LICENSOR_QRCODE_URL_KEY:
            licensorInfromation.setQrCodeUrl(in.nextString());
            break;
        case Convention.OPEN_PLATFORM_AUTH_LICENSOR_BUSINESS_INFO_KEY:
            readBusinessInfo(in, licensorInfromation);
            break;
        default:
            if (in.hasNext()) {
                String value = in.nextString();
                logger.warn(LOG_UNKNOWN_JSON_KEY, key, value);
            }
        }
    }

    in.endObject();
    model.setLicensorInfromation(licensorInfromation);
}