com.google.gson.internal.Streams Java Examples

The following examples show how to use com.google.gson.internal.Streams. 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 Project: amazon-kinesis-analytics-taxi-consumer   Author: aws-samples   File: Event.java    License: Apache License 2.0 6 votes vote down vote up
public static Event parseEvent(byte[] event) {
  //parse the event payload and remove the type attribute
  JsonReader jsonReader =  new JsonReader(new InputStreamReader(new ByteArrayInputStream(event)));
  JsonElement jsonElement = Streams.parse(jsonReader);
  JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(TYPE_FIELD);

  if (labelJsonElement == null) {
    throw new IllegalArgumentException("Event does not define a type field: " + new String(event));
  }

  //convert json to POJO, based on the type attribute
  switch (labelJsonElement.getAsString()) {
    case "watermark":
      return gson.fromJson(jsonElement, WatermarkEvent.class);
    case "trip":
      return gson.fromJson(jsonElement, TripEvent.class);
    default:
      throw new IllegalArgumentException("Found unsupported event type: " + labelJsonElement.getAsString());
  }
}
 
Example #2
Source Project: letv   Author: JackChan1999   File: Gson.java    License: Apache License 2.0 6 votes vote down vote up
public void toJson(JsonElement jsonElement, JsonWriter writer) throws JsonIOException {
    boolean oldLenient = writer.isLenient();
    writer.setLenient(true);
    boolean oldHtmlSafe = writer.isHtmlSafe();
    writer.setHtmlSafe(this.htmlSafe);
    boolean oldSerializeNulls = writer.getSerializeNulls();
    writer.setSerializeNulls(this.serializeNulls);
    try {
        Streams.write(jsonElement, writer);
        writer.setLenient(oldLenient);
        writer.setHtmlSafe(oldHtmlSafe);
        writer.setSerializeNulls(oldSerializeNulls);
    } catch (Throwable e) {
        throw new JsonIOException(e);
    } catch (Throwable th) {
        writer.setLenient(oldLenient);
        writer.setHtmlSafe(oldHtmlSafe);
        writer.setSerializeNulls(oldSerializeNulls);
    }
}
 
Example #3
Source Project: flink-stream-processing-refarch   Author: aws-samples   File: Event.java    License: Apache License 2.0 6 votes vote down vote up
public static Event parseEvent(byte[] event) {
  //parse the event payload and remove the type attribute
  JsonReader jsonReader =  new JsonReader(new InputStreamReader(new ByteArrayInputStream(event)));
  JsonElement jsonElement = Streams.parse(jsonReader);
  JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(TYPE_FIELD);

  if (labelJsonElement == null) {
    throw new IllegalArgumentException("Event does not define a type field: " + new String(event));
  }

  //convert json to POJO, based on the type attribute
  switch (labelJsonElement.getAsString()) {
    case "watermark":
      return gson.fromJson(jsonElement, WatermarkEvent.class);
    case "trip":
      return gson.fromJson(jsonElement, TripEvent.class);
    default:
      throw new IllegalArgumentException("Found unsupported event type: " + labelJsonElement.getAsString());
  }
}
 
Example #4
Source Project: MiBandDecompiled   Author: vishnudevk   File: JsonElement.java    License: Apache License 2.0 6 votes vote down vote up
public String toString()
{
    String s;
    try
    {
        StringWriter stringwriter = new StringWriter();
        JsonWriter jsonwriter = new JsonWriter(stringwriter);
        jsonwriter.setLenient(true);
        Streams.write(this, jsonwriter);
        s = stringwriter.toString();
    }
    catch (IOException ioexception)
    {
        throw new AssertionError(ioexception);
    }
    return s;
}
 
Example #5
Source Project: MiBandDecompiled   Author: vishnudevk   File: o.java    License: Apache License 2.0 6 votes vote down vote up
public void write(JsonWriter jsonwriter, Object obj)
{
    if (a == null)
    {
        a().write(jsonwriter, obj);
        return;
    }
    if (obj == null)
    {
        jsonwriter.nullValue();
        return;
    } else
    {
        Streams.write(a.serialize(obj, d.getType(), c.c), jsonwriter);
        return;
    }
}
 
Example #6
Source Project: gson   Author: google   File: JsonParserTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testReadWriteTwoObjects() throws Exception {
  Gson gson = new Gson();
  CharArrayWriter writer = new CharArrayWriter();
  BagOfPrimitives expectedOne = new BagOfPrimitives(1, 1, true, "one");
  writer.write(gson.toJson(expectedOne).toCharArray());
  BagOfPrimitives expectedTwo = new BagOfPrimitives(2, 2, false, "two");
  writer.write(gson.toJson(expectedTwo).toCharArray());
  CharArrayReader reader = new CharArrayReader(writer.toCharArray());

  JsonReader parser = new JsonReader(reader);
  parser.setLenient(true);
  JsonElement element1 = Streams.parse(parser);
  JsonElement element2 = Streams.parse(parser);
  BagOfPrimitives actualOne = gson.fromJson(element1, BagOfPrimitives.class);
  assertEquals("one", actualOne.stringValue);
  BagOfPrimitives actualTwo = gson.fromJson(element2, BagOfPrimitives.class);
  assertEquals("two", actualTwo.stringValue);
}
 
Example #7
Source Project: incubator-gobblin   Author: apache   File: GsonInterfaceAdapter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public R read(JsonReader in) throws IOException {
  JsonElement element = Streams.parse(in);
  if (element.isJsonNull()) {
    return readNull();
  }
  JsonObject jsonObject = element.getAsJsonObject();

  if (this.typeToken.getRawType() == Optional.class) {
    if (jsonObject.has(OBJECT_TYPE)) {
      return (R) Optional.of(readValue(jsonObject, null));
    } else if (jsonObject.entrySet().isEmpty()) {
      return (R) Optional.absent();
    } else {
      throw new IOException("No class found for Optional value.");
    }
  }
  return this.readValue(jsonObject, this.typeToken);
}
 
Example #8
Source Project: framework   Author: Odoo-mobile   File: Gson.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Writes the JSON for {@code jsonElement} to {@code writer}.
 * @throws JsonIOException if there was a problem writing to the writer
 */
public void toJson(JsonElement jsonElement, JsonWriter writer) throws JsonIOException {
  boolean oldLenient = writer.isLenient();
  writer.setLenient(true);
  boolean oldHtmlSafe = writer.isHtmlSafe();
  writer.setHtmlSafe(htmlSafe);
  boolean oldSerializeNulls = writer.getSerializeNulls();
  writer.setSerializeNulls(serializeNulls);
  try {
    Streams.write(jsonElement, writer);
  } catch (IOException e) {
    throw new JsonIOException(e);
  } finally {
    writer.setLenient(oldLenient);
    writer.setHtmlSafe(oldHtmlSafe);
    writer.setSerializeNulls(oldSerializeNulls);
  }
}
 
Example #9
Source Project: weixin-java-tools   Author: chanjarster   File: WxCpServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
public String getJsapiTicket(boolean forceRefresh) throws WxErrorException {
  if (forceRefresh) {
    wxCpConfigStorage.expireJsapiTicket();
  }
  if (wxCpConfigStorage.isJsapiTicketExpired()) {
    synchronized (globalJsapiTicketRefreshLock) {
      if (wxCpConfigStorage.isJsapiTicketExpired()) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket";
        String responseContent = execute(new SimpleGetRequestExecutor(), url, null);
        JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
        JsonObject tmpJsonObject = tmpJsonElement.getAsJsonObject();
        String jsapiTicket = tmpJsonObject.get("ticket").getAsString();
        int expiresInSeconds = tmpJsonObject.get("expires_in").getAsInt();
        wxCpConfigStorage.updateJsapiTicket(jsapiTicket, expiresInSeconds);
      }
    }
  }
  return wxCpConfigStorage.getJsapiTicket();
}
 
Example #10
Source Project: weixin-java-tools   Author: chanjarster   File: WxCpServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<WxCpUser> userList(Integer departId, Boolean fetchChild, Integer status) throws WxErrorException {
  String url = "https://qyapi.weixin.qq.com/cgi-bin/user/list?department_id=" + departId;
  String params = "";
  if (fetchChild != null) {
    params += "&fetch_child=" + (fetchChild ? "1" : "0");
  }
  if (status != null) {
    params += "&status=" + status;
  } else {
    params += "&status=0";
  }

  String responseContent = get(url, params);
  JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
  return WxCpGsonBuilder.INSTANCE.create()
      .fromJson(
          tmpJsonElement.getAsJsonObject().get("userlist"),
          new TypeToken<List<WxCpUser>>() { }.getType()
      );
}
 
Example #11
Source Project: weixin-java-tools   Author: chanjarster   File: WxCpServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<WxCpUser> departGetUsers(Integer departId, Boolean fetchChild, Integer status) throws WxErrorException {
  String url = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?department_id=" + departId;
  String params = "";
  if (fetchChild != null) {
    params += "&fetch_child=" + (fetchChild ? "1" : "0");
  }
  if (status != null) {
    params += "&status=" + status;
  } else {
    params += "&status=0";
  }

  String responseContent = get(url, params);
  JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
  return WxCpGsonBuilder.INSTANCE.create()
      .fromJson(
          tmpJsonElement.getAsJsonObject().get("userlist"),
          new TypeToken<List<WxCpUser>>() { }.getType()
      );
}
 
Example #12
Source Project: weixin-java-tools   Author: chanjarster   File: WxMpServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
public String getJsapiTicket(boolean forceRefresh) throws WxErrorException {
  if (forceRefresh) {
    wxMpConfigStorage.expireJsapiTicket();
  }
  if (wxMpConfigStorage.isJsapiTicketExpired()) {
    synchronized (globalJsapiTicketRefreshLock) {
      if (wxMpConfigStorage.isJsapiTicketExpired()) {
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi";
        String responseContent = execute(new SimpleGetRequestExecutor(), url, null);
        JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
        JsonObject tmpJsonObject = tmpJsonElement.getAsJsonObject();
        String jsapiTicket = tmpJsonObject.get("ticket").getAsString();
        int expiresInSeconds = tmpJsonObject.get("expires_in").getAsInt();
        wxMpConfigStorage.updateJsapiTicket(jsapiTicket, expiresInSeconds);
      }
    }
  }
  return wxMpConfigStorage.getJsapiTicket();
}
 
Example #13
Source Project: java-trader   Author: zhugf   File: JsonUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static String json2str(JsonElement json, Boolean pretty) {
   try {
       StringWriter stringWriter = new StringWriter(1024);
        JsonWriter jsonWriter = new JsonWriter(stringWriter);
        if ( pretty!=null && pretty ) {
            jsonWriter.setIndent("  ");
        }
        jsonWriter.setLenient(true);
        Streams.write(json, jsonWriter);
        return stringWriter.toString();
   }catch(Throwable t) {
       return json.toString();
   }
}
 
Example #14
Source Project: letv   Author: JackChan1999   File: Gson.java    License: Apache License 2.0 5 votes vote down vote up
public void toJson(Object src, Type typeOfSrc, Appendable writer) throws JsonIOException {
    try {
        toJson(src, typeOfSrc, newJsonWriter(Streams.writerForAppendable(writer)));
    } catch (Throwable e) {
        throw new JsonIOException(e);
    }
}
 
Example #15
Source Project: letv   Author: JackChan1999   File: Gson.java    License: Apache License 2.0 5 votes vote down vote up
public void toJson(JsonElement jsonElement, Appendable writer) throws JsonIOException {
    try {
        toJson(jsonElement, newJsonWriter(Streams.writerForAppendable(writer)));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #16
Source Project: letv   Author: JackChan1999   File: TreeTypeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public T read(JsonReader in) throws IOException {
    if (this.deserializer == null) {
        return delegate().read(in);
    }
    JsonElement value = Streams.parse(in);
    if (value.isJsonNull()) {
        return null;
    }
    return this.deserializer.deserialize(value, this.typeToken.getType(), this.gson.deserializationContext);
}
 
Example #17
Source Project: letv   Author: JackChan1999   File: TreeTypeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public void write(JsonWriter out, T value) throws IOException {
    if (this.serializer == null) {
        delegate().write(out, value);
    } else if (value == null) {
        out.nullValue();
    } else {
        Streams.write(this.serializer.serialize(value, this.typeToken.getType(), this.gson.serializationContext), out);
    }
}
 
Example #18
Source Project: letv   Author: JackChan1999   File: JsonElement.java    License: Apache License 2.0 5 votes vote down vote up
public String toString() {
    try {
        StringWriter stringWriter = new StringWriter();
        JsonWriter jsonWriter = new JsonWriter(stringWriter);
        jsonWriter.setLenient(true);
        Streams.write(this, jsonWriter);
        return stringWriter.toString();
    } catch (IOException e) {
        throw new AssertionError(e);
    }
}
 
Example #19
Source Project: synthea   Author: synthetichealth   File: InnerClassTypeAdapterFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
  if (type.getRawType() != baseType) {
    return null;
  }

  return new TypeAdapter<R>() {
    @Override public R read(JsonReader in) throws IOException {
      JsonElement jsonElement = Streams.parse(in);
      JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
      if (labelJsonElement == null) {
        throw new JsonParseException("cannot deserialize " + baseType
            + " because it does not define a field named " + typeFieldName);
      }
      String label = labelJsonElement.getAsString();
      
      try {
        String subclassName = baseType.getName() + "$" + label.replaceAll("\\s", "");
        Class<?> subclass = Class.forName(subclassName);
        @SuppressWarnings("unchecked")
        TypeAdapter<R> delegate = (TypeAdapter<R>) gson.getDelegateAdapter(
            InnerClassTypeAdapterFactory.this, TypeToken.get(subclass));
        if (delegate == null) {
          throw new JsonParseException("cannot deserialize " + baseType + " subtype named "
              + label);
        }
        return delegate.fromJsonTree(jsonElement);
      } catch (ClassNotFoundException e) {
        throw new JsonParseException("cannot deserialize " + baseType + " subtype named "
            + label);
      }
    }

    @Override public void write(JsonWriter out, R value) throws IOException {
      throw new NotImplementedException("Write not implemented for InnerClassTypeAdapter");
    }
  }.nullSafe();
}
 
Example #20
Source Project: Wizardry   Author: TeamWizardry   File: ManifestUtils.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void writeJsonToFile(JsonObject object, File file) {
	try (JsonWriter writer = new JsonWriter(Files.newWriter(file, Charset.defaultCharset()))) {
		Streams.write(object, writer);
	} catch (IOException e) {
		Wizardry.LOGGER.error("    > SOMETHING WENT WRONG! Could not create or write to file! Customizations to recipes and modules will be reset every time you load the game!");
		e.printStackTrace();
	}
}
 
Example #21
Source Project: mybatis-gson   Author: jneat   File: JsonElementTypeHandler.java    License: MIT License 5 votes vote down vote up
@Override
public void setNonNullParameter(PreparedStatement ps, int i, JsonElement parameter, JdbcType jdbcType) throws SQLException {
    try {
        StringWriter sw = new StringWriter();
        JsonWriter jsonWriter = new JsonWriter(sw);
        jsonWriter.setLenient(false);
        Streams.write(parameter, jsonWriter);
        ps.setString(i, sw.toString());
    } catch (IOException ex) {
        throw new RuntimeException(ex.getMessage(), ex);
    }
}
 
Example #22
Source Project: MiBandDecompiled   Author: vishnudevk   File: Gson.java    License: Apache License 2.0 5 votes vote down vote up
public void toJson(JsonElement jsonelement, Appendable appendable)
{
    try
    {
        toJson(jsonelement, a(Streams.writerForAppendable(appendable)));
        return;
    }
    catch (IOException ioexception)
    {
        throw new RuntimeException(ioexception);
    }
}
 
Example #23
Source Project: MiBandDecompiled   Author: vishnudevk   File: Gson.java    License: Apache License 2.0 5 votes vote down vote up
public void toJson(Object obj, Type type, Appendable appendable)
{
    try
    {
        toJson(obj, type, a(Streams.writerForAppendable(appendable)));
        return;
    }
    catch (IOException ioexception)
    {
        throw new JsonIOException(ioexception);
    }
}
 
Example #24
Source Project: MiBandDecompiled   Author: vishnudevk   File: o.java    License: Apache License 2.0 5 votes vote down vote up
public Object read(JsonReader jsonreader)
{
    if (b == null)
    {
        return a().read(jsonreader);
    }
    JsonElement jsonelement = Streams.parse(jsonreader);
    if (jsonelement.isJsonNull())
    {
        return null;
    } else
    {
        return b.deserialize(jsonelement, d.getType(), c.b);
    }
}
 
Example #25
Source Project: gson   Author: google   File: Gson.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Writes out the equivalent JSON for a tree of {@link JsonElement}s.
 *
 * @param jsonElement root of a tree of {@link JsonElement}s
 * @param writer Writer to which the Json representation needs to be written
 * @throws JsonIOException if there was a problem writing to the writer
 * @since 1.4
 */
public void toJson(JsonElement jsonElement, Appendable writer) throws JsonIOException {
  try {
    JsonWriter jsonWriter = newJsonWriter(Streams.writerForAppendable(writer));
    toJson(jsonElement, jsonWriter);
  } catch (IOException e) {
    throw new JsonIOException(e);
  }
}
 
Example #26
Source Project: gson   Author: google   File: TreeTypeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override public T read(JsonReader in) throws IOException {
  if (deserializer == null) {
    return delegate().read(in);
  }
  JsonElement value = Streams.parse(in);
  if (value.isJsonNull()) {
    return null;
  }
  return deserializer.deserialize(value, typeToken.getType(), context);
}
 
Example #27
Source Project: gson   Author: google   File: TreeTypeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override public void write(JsonWriter out, T value) throws IOException {
  if (serializer == null) {
    delegate().write(out, value);
    return;
  }
  if (value == null) {
    out.nullValue();
    return;
  }
  JsonElement tree = serializer.serialize(value, typeToken.getType(), context);
  Streams.write(tree, out);
}
 
Example #28
Source Project: gson   Author: google   File: JsonElement.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a String representation of this element.
 */
@Override
public String toString() {
  try {
    StringWriter stringWriter = new StringWriter();
    JsonWriter jsonWriter = new JsonWriter(stringWriter);
    jsonWriter.setLenient(true);
    Streams.write(this, jsonWriter);
    return stringWriter.toString();
  } catch (IOException e) {
    throw new AssertionError(e);
  }
}
 
Example #29
Source Project: problem   Author: zalando   File: CustomProblemAdapter.java    License: MIT License 5 votes vote down vote up
@Override
public void write(final JsonWriter out, final T value) throws IOException {
    final JsonElement element = delegate.toJsonTree(value);
    final JsonObject object = element.getAsJsonObject();

    final URI problemType = URITypeAdapter.TYPE.fromJsonTree(object.remove("type"));
    object.add("type", URITypeAdapter.TYPE.toJsonTree(problemType));

    if (value instanceof AbstractThrowableProblem) {
        flattenParameters(object);
    }

    if (value instanceof Throwable) {
        // Get rid of unwanted fields.
        object.remove("detailMessage");
        object.remove("suppressedExceptions");
        object.remove("stackTrace");

        if (stackTraces) {
            object.add("stacktrace", gson.getAdapter(String[].class)
                    .toJsonTree(stream(((Throwable) value).getStackTrace())
                            .map(Object::toString)
                            .toArray(String[]::new)));
        }
    }

    Streams.write(element, out);
}
 
Example #30
Source Project: incubator-gobblin   Author: apache   File: GsonInterfaceAdapter.java    License: Apache License 2.0 5 votes vote down vote up
private <S> void writeObject(S value, JsonWriter out) throws IOException {
  if (value != null) {
    JsonObject jsonObject = new JsonObject();
    jsonObject.add(OBJECT_TYPE, new JsonPrimitive(value.getClass().getName()));
    TypeAdapter<S> delegate =
        (TypeAdapter<S>) this.gson.getDelegateAdapter(this.factory, TypeToken.get(value.getClass()));
    jsonObject.add(OBJECT_DATA, delegate.toJsonTree(value));
    Streams.write(jsonObject, out);
  } else {
    out.nullValue();
  }
}