Java Code Examples for com.google.gson.stream.JsonReader#beginArray()

The following examples show how to use com.google.gson.stream.JsonReader#beginArray() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CustomMessageEntry.java    From ForgeHax with MIT License 6 votes vote down vote up
@Override
public void deserialize(JsonReader reader) throws IOException {
  reader.beginObject();
  
  while (reader.hasNext()) {
    switch (reader.nextName()) {
      case "messages":
        reader.beginArray();
        while (reader.hasNext()) {
          reader.beginObject();
          MessageEntry entry = new MessageEntry(UUID.fromString(reader.nextName()));
          entry.deserialize(reader);
          messages.add(entry);
          reader.endObject();
        }
        reader.endArray();
        break;
      default:
        break;
    }
  }
  
  reader.endObject();
}
 
Example 2
Source File: SBSApiBase.java    From iview-android-tv with MIT License 6 votes vote down vote up
private List<EpisodeModel> readEntriesArray(JsonReader reader) throws IOException {
    reader.beginArray();
    Gson gson = new GsonBuilder().create();
    List<EpisodeModel> all = new ArrayList<>();
    while (reader.hasNext()) {
        try {
            Entry entry = gson.fromJson(reader, Entry.class);
            EpisodeModel ep = EpisodeModel.create(entry);
            all.add(ep);
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
    }
    reader.endArray();
    return all;
}
 
Example 3
Source File: SpeechTimestampTypeAdapter.java    From java-sdk with Apache License 2.0 6 votes vote down vote up
@Override
public SpeechTimestamp read(JsonReader reader) throws IOException {
  if (reader.peek() == JsonToken.NULL) {
    reader.nextNull();
    return null;
  }

  final SpeechTimestamp speechTimestamp = new SpeechTimestamp();
  reader.beginArray();

  if (reader.peek() == JsonToken.STRING) {
    speechTimestamp.setWord(reader.nextString());
  }
  if (reader.peek() == JsonToken.NUMBER) {
    speechTimestamp.setStartTime(reader.nextDouble());
  }
  if (reader.peek() == JsonToken.NUMBER) {
    speechTimestamp.setEndTime(reader.nextDouble());
  }

  reader.endArray();
  return speechTimestamp;
}
 
Example 4
Source File: MarkTimingTypeAdapter.java    From java-sdk with Apache License 2.0 6 votes vote down vote up
@Override
public MarkTiming read(JsonReader in) throws IOException {
  if (in.peek() == JsonToken.NULL) {
    in.nextNull();
    return null;
  }

  final MarkTiming markTiming = new MarkTiming();
  in.beginArray();

  if (in.peek() == JsonToken.STRING) {
    markTiming.setMark(in.nextString());
  }
  if (in.peek() == JsonToken.NUMBER) {
    markTiming.setTime(in.nextDouble());
  }

  in.endArray();
  return markTiming;
}
 
Example 5
Source File: QuerySolrIT.java    From nifi with Apache License 2.0 6 votes vote down vote up
private int returnCheckSumForArrayOfJsonObjects(JsonReader reader) throws IOException {
    int checkSum = 0;
    reader.beginArray();
    while (reader.hasNext()) {
        reader.beginObject();
        while (reader.hasNext()) {
            if (reader.nextName().equals("count")) {
                checkSum += reader.nextInt();
            } else {
                reader.skipValue();
            }
        }
        reader.endObject();
    }
    reader.endArray();
    return checkSum;
}
 
Example 6
Source File: TapchatService.java    From tapchat-android with Apache License 2.0 6 votes vote down vote up
private void oobInclude(String path) throws Exception {
    mLoadingOobBacklog = true;

    Response response = mAPI.oobInclude(path.substring(1));

    JsonReader reader = new JsonReader(new InputStreamReader(response.getBody().in()));
    reader.beginArray();
    while (reader.hasNext()) {
        Message message = mGson.fromJson(reader, Message.class);
        handleMessage(message);
    }
    reader.endArray();
    reader.close();

    mLoadingOobBacklog = false;
    handleMessageCache();
}
 
Example 7
Source File: EmptyDataTest.java    From restcountries with Mozilla Public License 2.0 6 votes vote down vote up
@Before
public void before() throws IOException {
    InputStream is = this.getClass().getClassLoader()
            .getResourceAsStream("countriesV2.json");
    Gson gson = new Gson();
    JsonReader reader = new JsonReader(new InputStreamReader(is, "UTF-8"));
    countries = new ArrayList<>();
    reader.beginArray();
    while (reader.hasNext()) {
        BaseCountry country = gson.fromJson(reader, BaseCountry.class);
        countries.add(country);
    }
    reader.endArray();
    reader.close();
}
 
Example 8
Source File: ListOfListOfPointCoordinatesTypeAdapter.java    From mapbox-java with MIT License 5 votes vote down vote up
@Override
public List<List<Point>> read(JsonReader in) throws IOException {

  if (in.peek() == JsonToken.NULL) {
    throw new NullPointerException();
  }

  if (in.peek() == JsonToken.BEGIN_ARRAY) {

    in.beginArray();
    List<List<Point>> points = new ArrayList<>();

    while (in.peek() == JsonToken.BEGIN_ARRAY) {

      in.beginArray();
      List<Point> listOfPoints = new ArrayList<>();

      while (in.peek() == JsonToken.BEGIN_ARRAY) {
        listOfPoints.add(readPoint(in));
      }
      in.endArray();
      points.add(listOfPoints);
    }
    in.endArray();

    return points;
  }

  throw new GeoJsonException("coordinates should be array of array of array of double");
}
 
Example 9
Source File: IndexTMDB.java    From quaerite with Apache License 2.0 5 votes vote down vote up
private static List<String> extractNamesFromArrayOfObjections(JsonReader jsonReader) throws IOException {
    List<String> names = new ArrayList<>();
    jsonReader.beginArray();
    if (jsonReader.peek().equals(JsonToken.END_ARRAY)) {
        jsonReader.endArray();
        return names;
    }
    jsonReader.beginObject();
    while (jsonReader.hasNext()) {
        String name = jsonReader.nextName();
        if ("name".equals(name)) {
            String s = jsonReader.nextString();
            if (!StringUtils.isBlank(s)) {
                names.add(s);
            }
        } else {
            jsonReader.skipValue();
        }
        if (jsonReader.peek().equals(JsonToken.END_OBJECT)) {
            jsonReader.endObject();
            if (jsonReader.peek().equals(JsonToken.END_ARRAY)) {
                break;
            } else {
                jsonReader.beginObject();
            }
        } else if (jsonReader.peek().equals(JsonToken.BEGIN_OBJECT)) {
            jsonReader.beginObject();
        }
    }
    jsonReader.endArray();
    return names;
}
 
Example 10
Source File: Color.java    From BlockMap with MIT License 5 votes vote down vote up
@Override
public Color read(JsonReader in) throws IOException {
	in.beginArray();
	Color color;
	if (in.hasNext())
		color = new Color(
				Float.intBitsToFloat(in.nextInt()),
				Float.intBitsToFloat(in.nextInt()),
				Float.intBitsToFloat(in.nextInt()),
				Float.intBitsToFloat(in.nextInt()));
	else
		color = new Color(0, 0, 0, 0);
	in.endArray();
	return color;
}
 
Example 11
Source File: SessionQueryAll.java    From pxgrid-rest-ws with Apache License 2.0 5 votes vote down vote up
public static void postAndStreamPrint(HttpsURLConnection httpsConn, Object postObject) throws IOException {
	Gson gson = new GsonBuilder().registerTypeAdapter(OffsetDateTime.class, new OffsetDateTimeAdapter()).create();
	httpsConn.setRequestMethod("POST");
	httpsConn.setRequestProperty("Content-Type", "application/json");
	httpsConn.setRequestProperty("Accept", "application/json");
	httpsConn.setDoInput(true);
	httpsConn.setDoOutput(true);
	OutputStreamWriter osw = new OutputStreamWriter(httpsConn.getOutputStream());
	osw.write(gson.toJson(postObject));
	osw.flush();

	int status = httpsConn.getResponseCode();
	logger.info("Response status={}", status);
	
	if (status < HttpURLConnection.HTTP_BAD_REQUEST) {
		try (InputStream in = httpsConn.getInputStream()) {
			JsonReader jreader = new JsonReader(new InputStreamReader(in));
			jreader.beginObject();
			String name = jreader.nextName();
			if ("sessions".equals(name)) {
				int count = 0;
				jreader.beginArray();
				while (jreader.hasNext()) {
					Session session = gson.fromJson(jreader, Session.class);
					System.out.println("session=" + session);
					count++;
				}
				System.out.println("count=" + count);
			}
		}
	} else {
		try (InputStream in = httpsConn.getErrorStream()) {
			String content = IOUtils.toString(in, StandardCharsets.UTF_8);
			System.out.println("Content: " + content);
		}
	}
}
 
Example 12
Source File: JsonErrorDocumentConsumer.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
private String readJson(final JsonReader reader) throws IOException {
  StringBuilder sb = new StringBuilder();

  while (reader.hasNext()) {
    JsonToken token = reader.peek();
    if (token == JsonToken.NAME) {
      if (sb.length() > 0) {
        sb.append(",");
      }
      String name = reader.nextName();
      sb.append("\"").append(name).append("\"").append(":");
    } else if (token == JsonToken.BEGIN_OBJECT) {
      reader.beginObject();
      sb.append("{")
          .append(readJson(reader))
          .append("}");
      reader.endObject();
    } else if (token == JsonToken.BEGIN_ARRAY) {
      reader.beginArray();
      sb.append("[")
          .append(readJson(reader))
          .append("]");
      reader.endArray();
    } else {
      sb.append("\"")
          .append(reader.nextString())
          .append("\"");
    }
  }

  return sb.toString();
}
 
Example 13
Source File: JsonServiceDocumentConsumer.java    From cloud-odata-java with Apache License 2.0 5 votes vote down vote up
private void readContent(final JsonReader reader) throws IOException, EdmException, EntityProviderException {
  currentHandledObjectName = reader.nextName();
  if (FormatJson.ENTITY_SETS.equals(currentHandledObjectName)) {
    reader.beginArray();
    readEntitySets(reader);
    reader.endArray();
  }
}
 
Example 14
Source File: FeatureCollectionAdapter.java    From geogson with Apache License 2.0 5 votes vote down vote up
@Override
public FeatureCollection read(JsonReader in) throws IOException {
    FeatureCollection featureCollection = null;

    if (in.peek() == JsonToken.NULL) {
        in.nextNull();
    } else if (in.peek() == JsonToken.BEGIN_OBJECT) {
        in.beginObject();
        LinkedList<Feature> features = null;

        while (in.hasNext()) {
            String name = in.nextName();
            if ("features".equalsIgnoreCase(name)) {
                in.beginArray();
                features = new LinkedList<>();
                while(in.peek() == JsonToken.BEGIN_OBJECT) {
                    Feature feature = gson.fromJson(in, Feature.class);
                    features.add(feature);
                }
                in.endArray();
            } else {
                in.skipValue();
            }
        }

        if (features == null) {
            throw new IllegalArgumentException("Required field 'features' is missing");
        }

        featureCollection = new FeatureCollection(features);
        in.endObject();

    } else {
        throw new IllegalArgumentException("The given json is not a valid FeatureCollection: " + in.peek());
    }

    return featureCollection;
}
 
Example 15
Source File: QuerySolrIT.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Test
public void testFacetTrueButNull() throws IOException {
    SolrClient solrClient = createSolrClient();
    TestRunner runner = createRunnerWithSolrClient(solrClient);

    runner.setProperty("facet", "true");
    runner.setProperty("stats", "true");

    runner.enqueue(new ByteArrayInputStream(new byte[0]));
    runner.run();

    runner.assertTransferCount(QuerySolr.RESULTS, 1);
    runner.assertTransferCount(QuerySolr.FACETS, 1);
    runner.assertTransferCount(QuerySolr.STATS, 1);

    // Check for empty nestet Objects in JSON
    JsonReader reader = new JsonReader(new InputStreamReader(new ByteArrayInputStream(
            runner.getContentAsByteArray(runner.getFlowFilesForRelationship(QuerySolr.FACETS).get(0)))));
    reader.beginObject();
    while (reader.hasNext()) {
        if (reader.nextName().equals("facet_queries")) {
            reader.beginArray();
            assertFalse(reader.hasNext());
            reader.endArray();
        } else {
            reader.beginObject();
            assertFalse(reader.hasNext());
            reader.endObject();
        }
    }
    reader.endObject();

    JsonReader reader_stats = new JsonReader(new InputStreamReader(new ByteArrayInputStream(
            runner.getContentAsByteArray(runner.getFlowFilesForRelationship(QuerySolr.STATS).get(0)))));
    reader_stats.beginObject();
    assertEquals(reader_stats.nextName(), "stats_fields");
    reader_stats.beginObject();
    assertFalse(reader_stats.hasNext());
    reader_stats.endObject();
    reader_stats.endObject();

    reader.close();
    reader_stats.close();
    solrClient.close();
}
 
Example 16
Source File: MessageJsonSerializer.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Message read(JsonReader in) throws IOException {
    in.beginObject();
    Message.Kind kind = Message.Kind.UNKNOWN;
    String text = "";
    String rawMessage = null;
    ImmutableList.Builder<SourceFilePosition> positions =
            new ImmutableList.Builder<SourceFilePosition>();
    SourceFile legacyFile = SourceFile.UNKNOWN;
    SourcePosition legacyPosition = SourcePosition.UNKNOWN;
    while (in.hasNext()) {
        String name = in.nextName();
        if (name.equals(KIND)) {
            //noinspection StringToUpperCaseOrToLowerCaseWithoutLocale
            Message.Kind theKind = KIND_STRING_ENUM_MAP.inverse()
                    .get(in.nextString().toLowerCase());
            kind = (theKind != null) ? theKind : Message.Kind.UNKNOWN;
        } else if (name.equals(TEXT)) {
            text = in.nextString();
        } else if (name.equals(RAW_MESSAGE)) {
            rawMessage = in.nextString();
        } else if (name.equals(SOURCE_FILE_POSITIONS)) {
            switch (in.peek()) {
                case BEGIN_ARRAY:
                    in.beginArray();
                    while(in.hasNext()) {
                        positions.add(mSourceFilePositionTypeAdapter.read(in));
                    }
                    in.endArray();
                    break;
                case BEGIN_OBJECT:
                    positions.add(mSourceFilePositionTypeAdapter.read(in));
                    break;
                default:
                    in.skipValue();
                    break;
            }
        } else if (name.equals(LEGACY_SOURCE_PATH)) {
            legacyFile = new SourceFile(new File(in.nextString()));
        } else if (name.equals(LEGACY_POSITION)) {
            legacyPosition = mSourcePositionTypeAdapter.read(in);
        } else {
            in.skipValue();
        }
    }
    in.endObject();

    if (legacyFile != SourceFile.UNKNOWN || legacyPosition != SourcePosition.UNKNOWN) {
        positions.add(new SourceFilePosition(legacyFile, legacyPosition));
    }
    if (rawMessage == null) {
        rawMessage = text;
    }
    ImmutableList<SourceFilePosition> sourceFilePositions = positions.build();
    if (!sourceFilePositions.isEmpty()) {
        return new Message(kind, text, rawMessage, sourceFilePositions);
    } else {
        return new Message(kind, text, rawMessage, ImmutableList.of(SourceFilePosition.UNKNOWN));
    }
}
 
Example 17
Source File: ExtractorsTypeAdapter.java    From zap-extensions with Apache License 2.0 4 votes vote down vote up
@Override
public Extractors read(JsonReader in) throws IOException {
    Extractors extractors = new Extractors();

    in.beginObject();
    while (in.hasNext()) {
        switch (in.nextName()) {
            case Extractors.TYPE_FUNC:
                in.beginArray();
                List<String> funcs = new ArrayList<>();
                while (in.hasNext()) {
                    String aFunc = in.nextString();
                    aFunc = fixPattern(aFunc);
                    funcs.add(aFunc);
                }
                extractors.setFunc(funcs);
                in.endArray();
                break;
            case Extractors.TYPE_FILENAME:
                in.beginArray();
                List<String> filenames = new ArrayList<>();
                while (in.hasNext()) {
                    String aFilename = in.nextString();
                    aFilename = fixPattern(aFilename);
                    filenames.add(aFilename);
                }
                extractors.setFilename(filenames);
                in.endArray();
                break;
            case Extractors.TYPE_FILECONTENT:
                in.beginArray();
                List<String> filecontents = new ArrayList<>();
                while (in.hasNext()) {
                    String aFilecontent = in.nextString();
                    aFilecontent = fixPattern(aFilecontent);
                    filecontents.add(aFilecontent);
                }
                extractors.setFilecontent(filecontents);
                in.endArray();
                break;
            case Extractors.TYPE_URI:
                in.beginArray();
                List<String> uris = new ArrayList<>();
                while (in.hasNext()) {
                    String aUri = in.nextString();
                    aUri = fixPattern(aUri);
                    uris.add(aUri);
                }
                extractors.setUri(uris);
                in.endArray();
                break;
            case Extractors.TYPE_HASHES:
                in.beginObject();
                Map<String, String> hashes = new HashMap<String, String>();
                while (in.hasNext()) {
                    String key = in.nextName();
                    String value = in.nextString();
                    hashes.put(key, value);
                }
                extractors.setHashes(hashes);
                in.endObject();
                break;
            case "filecontentreplace":
                in.beginArray();
                while (in.hasNext()) {
                    @SuppressWarnings("unused")
                    String ignore = in.nextString(); // Ignore
                }
                in.endArray();
                break;
        }
    }
    in.endObject();

    return extractors;
}
 
Example 18
Source File: MTGPricePricer.java    From MtgDesktopCompanion with GNU General Public License v3.0 4 votes vote down vote up
@Override
public List<MagicPrice> getLocalePrice(MagicEdition ed, MagicCard card) throws IOException {
	if (getString(API_KEY).equals(""))
		throw new NullPointerException("API_KEY must be filled");

	MagicEdition selected = ed;
	if (ed == null)
		selected = card.getCurrentSet();

	String set = selected.getSet().replace(" ", "_");

	String url = getString("WS_URL") + "?apiKey=" + getString(API_KEY) + "&s=" + set;
	InputStream stream = URLTools.openConnection(url).getInputStream();
	List<MagicPrice> ret = new ArrayList<>();

	logger.info(getName() + " looking for price at " + url);

	try {
		JsonReader reader = new JsonReader(new InputStreamReader(stream));
		reader.setLenient(true);
		reader.beginObject();
		reader.nextName();
		reader.beginArray();

		String name = "";
		String fairPrice = "";
		String mtgpriceID = "";

		while (reader.hasNext()) {
			reader.beginObject();
			reader.nextName();
			mtgpriceID = (reader.nextString());
			reader.nextName();
			name = (reader.nextString());
			reader.nextName();
			fairPrice = (reader.nextString());
			reader.endObject();

			if (name.equalsIgnoreCase(card.getName())) {
				MagicPrice price = new MagicPrice();
				price.setCurrency("USD");
				price.setSeller(getName());
				price.setUrl(getString("WEBSITE") + "/sets/" + set + "/"+ mtgpriceID.substring(0, mtgpriceID.indexOf(set)));
				price.setValue(Double.parseDouble(fairPrice.replaceAll("\\$", "")));
				price.setQuality("NM");
				int start=mtgpriceID.indexOf(set) + set.length();
				price.setFoil(mtgpriceID.indexOf("true", start)>-1);
				price.setSite(getName());
				ret.add(price);
				reader.close();
				logger.info(getName() + " found " + ret.size() + " items");

				return ret;
			}
		}
		reader.close();
	} catch (Exception e) {

		return ret;
	}
	return ret;

}
 
Example 19
Source File: TestGetSolr.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Test
public void testRecordWriter() throws IOException, InitializationException {
    final org.apache.nifi.processors.solr.TestGetSolr.TestableProcessor proc = new org.apache.nifi.processors.solr.TestGetSolr.TestableProcessor(solrClient);

    TestRunner runner = createDefaultTestRunner(proc);
    runner.setProperty(GetSolr.RETURN_TYPE, GetSolr.MODE_REC.getValue());
    runner.setProperty(GetSolr.RETURN_FIELDS, "id,created,integer_single");
    runner.setProperty(GetSolr.BATCH_SIZE, "10");

    final String outputSchemaText = new String(Files.readAllBytes(Paths.get("src/test/resources/test-schema.avsc")));

    final JsonRecordSetWriter jsonWriter = new JsonRecordSetWriter();
    runner.addControllerService("writer", jsonWriter);
    runner.setProperty(jsonWriter, SchemaAccessUtils.SCHEMA_ACCESS_STRATEGY, SchemaAccessUtils.SCHEMA_TEXT_PROPERTY);
    runner.setProperty(jsonWriter, SchemaAccessUtils.SCHEMA_TEXT, outputSchemaText);
    runner.setProperty(jsonWriter, "Pretty Print JSON", "true");
    runner.setProperty(jsonWriter, "Schema Write Strategy", "full-schema-attribute");
    runner.enableControllerService(jsonWriter);
    runner.setProperty(SolrUtils.RECORD_WRITER, "writer");

    runner.run(1,true, true);
    runner.assertQueueEmpty();
    runner.assertAllFlowFilesTransferred(GetSolr.REL_SUCCESS, 1);
    runner.assertAllFlowFilesContainAttribute(CoreAttributes.MIME_TYPE.key());

    // Check for valid json
    JsonReader reader = new JsonReader(new InputStreamReader(new ByteArrayInputStream(
            runner.getContentAsByteArray(runner.getFlowFilesForRelationship(GetSolr.REL_SUCCESS).get(0)))));
    reader.beginArray();
    int controlScore = 0;
    while (reader.hasNext()) {
        reader.beginObject();
        while (reader.hasNext()) {
            if (reader.nextName().equals("integer_single"))
                controlScore += reader.nextInt();
            else
                reader.skipValue();
        }
        reader.endObject();
    }
    assertEquals(controlScore, 45);
}
 
Example 20
Source File: TestQuerySolr.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Test
public void testFacetTrueButNull() throws IOException {
    SolrClient solrClient = createSolrClient();
    TestRunner runner = createRunnerWithSolrClient(solrClient);

    runner.setProperty("facet", "true");
    runner.setProperty("stats", "true");

    runner.enqueue(new ByteArrayInputStream(new byte[0]));
    runner.run();

    runner.assertTransferCount(QuerySolr.RESULTS, 1);
    runner.assertTransferCount(QuerySolr.FACETS, 1);
    runner.assertTransferCount(QuerySolr.STATS, 1);

    // Check for empty nestet Objects in JSON
    JsonReader reader = new JsonReader(new InputStreamReader(new ByteArrayInputStream(
            runner.getContentAsByteArray(runner.getFlowFilesForRelationship(QuerySolr.FACETS).get(0)))));
    reader.beginObject();
    while (reader.hasNext()) {
        if (reader.nextName().equals("facet_queries")) {
            reader.beginArray();
            assertFalse(reader.hasNext());
            reader.endArray();
        } else {
            reader.beginObject();
            assertFalse(reader.hasNext());
            reader.endObject();
        }
    }
    reader.endObject();

    JsonReader reader_stats = new JsonReader(new InputStreamReader(new ByteArrayInputStream(
            runner.getContentAsByteArray(runner.getFlowFilesForRelationship(QuerySolr.STATS).get(0)))));
    reader_stats.beginObject();
    assertEquals(reader_stats.nextName(), "stats_fields");
    reader_stats.beginObject();
    assertFalse(reader_stats.hasNext());
    reader_stats.endObject();
    reader_stats.endObject();

    reader.close();
    reader_stats.close();
    solrClient.close();
}