下面列出了怎么用com.google.gson.JsonObject的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public CompletableFuture<JsonObject> getInternalInfoAsync(String topic) {
TopicName tn = validateTopic(topic);
WebTarget path = topicPath(tn, "internal-info");
final CompletableFuture<JsonObject> future = new CompletableFuture<>();
asyncGetRequest(path,
new InvocationCallback<String>() {
@Override
public void completed(String response) {
JsonObject json = new Gson().fromJson(response, JsonObject.class);
future.complete(json);
}
@Override
public void failed(Throwable throwable) {
future.completeExceptionally(getApiException(throwable.getCause()));
}
});
return future;
}
static JsonObject getTransactionObject(Transaction source, JsonSerializationContext context) {
JsonObject object = new JsonObject();
object.add("Id", context.serialize(source.getId()));
object.add("Tag", context.serialize(source.getTag()));
object.add("CreationDate", context.serialize(source.getCreationDate()));
object.add("AuthorId", context.serialize(source.getAuthorId()));
object.add("CreditedUserId", context.serialize(source.getCreditedUserId()));
object.add("DebitedFunds", context.serialize(source.getDebitedFunds()));
object.add("CreditedFunds", context.serialize(source.getCreditedFunds()));
object.add("Fees", context.serialize(source.getFees()));
object.add("Status", context.serialize(source.getStatus()));
object.add("ResultCode", context.serialize(source.getResultCode()));
object.add("ResultMessage", context.serialize(source.getResultMessage()));
object.add("ExecutionDate", context.serialize(source.getExecutionDate()));
object.add("Type", context.serialize(source.getType()));
object.add("Nature", context.serialize(source.getNature()));
return object;
}
@Test
public void write() throws Exception {
JsonObject obj = new JsonObject();
BigInteger bigInteger = new BigInteger(Long.toString(Long.MAX_VALUE)).multiply(new BigInteger("128"));
obj.addProperty("bigInteger", bigInteger);
BigDecimal bigDecimal = new BigDecimal(Long.MAX_VALUE).multiply(new BigDecimal(1024));
obj.addProperty("bigDecimal", bigDecimal);
BsonDocument doc = Jsons.toBson(obj);
check(doc.get("bigInteger").getBsonType()).is(BsonType.DECIMAL128);
check(doc.get("bigInteger").asDecimal128().decimal128Value().bigDecimalValue().toBigInteger()).is(bigInteger);
check(doc.get("bigDecimal").getBsonType()).is(BsonType.DECIMAL128);
check(doc.get("bigDecimal").asDecimal128().decimal128Value().bigDecimalValue()).is(bigDecimal);
}
/**
* Generate data validation report.
*
* @param dvReport the dv report
* @return the string
*/
public String generateDataValidationReport(String dvReport) {
JsonDataValidationDashBoardReport boardReport = new JsonDataValidationDashBoardReport();
JsonElement jelement = new JsonParser().parse(dvReport);
JsonObject jobject = jelement.getAsJsonObject();
setNullViolations(jobject, boardReport);
setRegexViolations(jobject, boardReport);
setDataTypeChecks(jobject, boardReport);
setSchemaViolations(jobject, boardReport);
setMissingViolations(jobject, boardReport);
JsonElement jsonElement = new Gson().toJsonTree(boardReport, JsonDataValidationDashBoardReport.class);
jobject.add("DVSUMMARY", jsonElement);
return jobject.toString();
}
private JsonArray handleHeaders(MimeHeaders headers) throws IOException {
JsonArray response = new JsonArray();
if (headers != null) {
Iterator headersIterator = headers.getAllHeaders();
while(headersIterator.hasNext()) {
MimeHeader mimheader = (MimeHeader)headersIterator.next();
JsonObject header = new JsonObject();
header.addProperty("name", mimheader.getName());
header.addProperty("value", mimheader.getValue());
response.add(header);
}
}
return response;
}
@Override
public String getCardDetail(String cardId) throws WxErrorException {
JsonObject param = new JsonObject();
param.addProperty("card_id", cardId);
String responseContent = this.wxMpService.post(CARD_GET, param.toString());
// 判断返回值
JsonObject json = (new JsonParser()).parse(responseContent).getAsJsonObject();
String errcode = json.get("errcode").getAsString();
if (!"0".equals(errcode)) {
String errmsg = json.get("errmsg").getAsString();
throw new WxErrorException(WxError.builder()
.errorCode(Integer.valueOf(errcode)).errorMsg(errmsg)
.build());
}
return responseContent;
}
@Override
public Build createBuild(String name, JsonObject buildConfig) throws IOException {
JsonObject buildParams = new JsonObject();
buildParams.addProperty("type", buildType.getJsonValue());
buildParams.addProperty("incremental", false);
if (name != null)
buildParams.addProperty("name", name);
String bodyStr = buildParams.toString();
// System.out.println("StreamsBuildService: =======> POST body = " + bodyStr);
Request post = Request.Post(endpoint)
.addHeader("Authorization", getAuthorization())
.bodyString(bodyStr,
ContentType.APPLICATION_JSON);
Build build = Build.create(this, this, StreamsRestUtils.requestGsonResponse(executor, post));
return build;
}
public static ArrayList<Product> parseJsonArray(JsonArray jsonArray) {
ArrayList<Product> products = new ArrayList<>(jsonArray.size());
Gson gson = new Gson();
for (int i=0 ; i<jsonArray.size() ; i++) {
JsonObject jsonObject = jsonArray.get(i).getAsJsonObject();
Product product = gson.fromJson(jsonObject, Product.class);
// temp hack for build
for (int j=0 ; j<product.getImages().length ; j++) {
product.getImages()[j].setPath(product.getImages()[j].getPath().replace("-catalogmobile", ""));
}
products.add(product);
}
return products;
}
private void parseChildren(String path, JsonObject object, Element context, boolean hasResourceType) throws FHIRException {
reapComments(object, context);
List<Property> properties = context.getProperty().getChildProperties(context.getName(), null);
Set<String> processed = new HashSet<String>();
if (hasResourceType)
processed.add("resourceType");
processed.add("fhir_comments");
// note that we do not trouble ourselves to maintain the wire format order here - we don't even know what it was anyway
// first pass: process the properties
for (Property property : properties) {
parseChildItem(path, object, context, processed, property);
}
// second pass: check for things not processed
if (policy != ValidationPolicy.NONE) {
for (Entry<String, JsonElement> e : object.entrySet()) {
if (!processed.contains(e.getKey())) {
logError(line(e.getValue()), col(e.getValue()), path, IssueType.STRUCTURE, "Unrecognised property '@"+e.getKey()+"'", IssueSeverity.ERROR);
}
}
}
}
/**
* Loads the parsed data. How the data is loaded is defined by
* {@link JsonLoader#load(JsonObject, Gson)}.
*
* @return the loader instance, for chaining.
*/
public final JsonLoader load() {
try (FileReader in = new FileReader(Paths.get(path).toFile())) {
JsonParser parser = new JsonParser();
JsonArray array = (JsonArray) parser.parse(in);
Gson builder = new GsonBuilder().create();
for (int i = 0; i < array.size(); i++) {
JsonObject reader = (JsonObject) array.get(i);
load(reader, builder);
}
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
@Nullable
public static Object run(@NotNull Project project, @NotNull String className, @NotNull String serviceJsNameStrategy) throws ScriptException {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("className", className);
jsonObject.addProperty("projectName", project.getName());
jsonObject.addProperty("projectBasePath", project.getBasePath());
jsonObject.addProperty("defaultNaming", new DefaultServiceNameStrategy().getServiceName(new ServiceNameStrategyParameter(project, className)));
PhpClass aClass = PhpElementsUtil.getClass(project, className);
if(aClass != null) {
String relativePath = VfsUtil.getRelativePath(aClass.getContainingFile().getVirtualFile(), ProjectUtil.getProjectDir(aClass), '/');
if(relativePath != null) {
jsonObject.addProperty("relativePath", relativePath);
}
jsonObject.addProperty("absolutePath", aClass.getContainingFile().getVirtualFile().toString());
}
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
if(engine == null) {
return null;
}
return engine.eval("var __p = eval(" + jsonObject.toString() + "); result = function(args) { " + serviceJsNameStrategy + " }(__p)");
}
/**
* Create a JsonObject wrapping a raw {@code Pair<Long msec,T reading>>} sample.
* @param sample the raw sample
* @param id the sensor's Id
* @return the wrapped sample
*/
public static <T> JsonObject wrap(Pair<Long,T> sample, String id) {
JsonObject jo = new JsonObject();
jo.addProperty(KEY_ID, id);
jo.addProperty(KEY_TS, sample.getFirst());
T value = sample.getSecond();
if (value instanceof Number)
jo.addProperty(KEY_READING, (Number)sample.getSecond());
else if (value instanceof String)
jo.addProperty(KEY_READING, (String)sample.getSecond());
else if (value instanceof Boolean)
jo.addProperty(KEY_READING, (Boolean)sample.getSecond());
// else if (value instanceof array) {
// // TODO cvt to JsonArray
// }
// else if (value instanceof Object) {
// // TODO cvt to JsonObject
// }
else {
Class<?> clazz = value != null ? value.getClass() : Object.class;
throw new IllegalArgumentException("Unhandled value type: "+ clazz);
}
return jo;
}
public ResponseWrapper changeGroupAdmin(long gid, String appKey, String username)
throws APIConnectionException, APIRequestException {
Preconditions.checkArgument(gid > 0, "gid should more than 0.");
if (StringUtils.isTrimedEmpty(appKey) && StringUtils.isTrimedEmpty(username)) {
Preconditions.checkArgument(false, "appKey and username should not be null at the same time.");
}
JsonObject json = new JsonObject();
if (StringUtils.isNotEmpty(appKey)){
appKey=appKey.trim();
json.addProperty("appKey",appKey);
}
if (StringUtils.isNotEmpty(username)){
username=username.trim();
json.addProperty("username",username);
}
return _httpClient.sendPut(_baseUrl + groupPath + "/owner/" + gid,json.toString());
}
@Override
public void handleRequest(HttpServerExchange exchange) {
String sid = getQueryParameter(exchange, "sid");
String secret = getQueryParameter(exchange, "client_secret");
try {
ThreePidValidation pid = mgr.getValidated(sid, secret);
JsonObject obj = new JsonObject();
obj.addProperty("medium", pid.getMedium());
obj.addProperty("address", pid.getAddress());
obj.addProperty("validated_at", pid.getValidation().toEpochMilli());
respond(exchange, obj);
} catch (SessionNotValidatedException e) {
log.info("Session {} was requested but has not yet been validated", sid);
throw e;
}
}
public XpubFull (JsonObject json) {
this(
json.has("address") ? json.get("address").getAsString() : "",
json.has("n_tx") ? json.get("n_tx").getAsInt() : 0,
json.has("total_received") ? json.get("total_received").getAsLong() : 0,
json.has("total_sent") ? json.get("total_sent").getAsLong() : 0,
json.has("final_balance") ? json.get("final_balance").getAsLong() : 0,
json.has("change_index") ? json.get("change_index").getAsInt() : 0,
json.has("account_index") ? json.get("account_index").getAsInt() : 0,
json.has("gap_limit") ? json.get("gap_limit").getAsInt() : 0,
null
);
txs = new ArrayList<Transaction>();
for (JsonElement txElem : json.get("txs").getAsJsonArray()) {
JsonObject addrObj = txElem.getAsJsonObject();
txs.add(new Transaction(addrObj));
}
}
@Override
public JsonElement serialize(final JoinBatchInformation batch, final Type typeOfSrc, final JsonSerializationContext context) {
final JsonObject result = new JsonObject();
result.add("class", new JsonPrimitive(batch.getClass().getName()));
result.add("batchSize", new JsonPrimitive(batch.getBatchSize()));
result.add("task", new JsonPrimitive(batch.getTask().name()));
final Column column = batch.getColumn();
result.add("column", new JsonPrimitive(column.getsFamily() + "\u0000" + column.getsQualifier()));
final Span span = batch.getSpan();
result.add("span", new JsonPrimitive(span.getStart().getsRow() + "\u0000" + span.getEnd().getsRow()));
result.add("startInc", new JsonPrimitive(span.isStartInclusive()));
result.add("endInc", new JsonPrimitive(span.isEndInclusive()));
result.add("side", new JsonPrimitive(batch.getSide().name()));
result.add("joinType", new JsonPrimitive(batch.getJoinType().name()));
final String updateVarOrderString = Joiner.on(";").join(batch.getBs().getBindingNames());
final VariableOrder updateVarOrder = new VariableOrder(updateVarOrderString);
result.add("bindingSet", new JsonPrimitive(converter.convert(batch.getBs(), updateVarOrder)));
result.add("updateVarOrder", new JsonPrimitive(updateVarOrderString));
return result;
}
private boolean isValidCell(JsonObject matrixCell, Build build) {
if (!matrixCell.has("on")) {
return true;
}
JsonObject onCond = matrixCell.get("on").getAsJsonObject();
if (onCond.has("branch")) {
JsonElement branchCond = onCond.get("branch");
Set<String> allowedBranches;
if (branchCond.isJsonPrimitive()) {
allowedBranches = ImmutableSet.of(branchCond.getAsString());
} else if(branchCond.isJsonArray()) {
allowedBranches = ImmutableSet.copyOf(JsonUtils.jsonArrayToStringList(branchCond.getAsJsonArray()));
} else {
return false;
}
if (!allowedBranches.contains(build.branch)) {
return false;
}
}
return true;
}
public void merge(JsonObject dest, JsonObject source) {
for (Entry<String, JsonElement> e : source.entrySet()) {
if (dest.has(e.getKey())) {
if (e.getValue() instanceof JsonObject && dest.get(e.getKey()) instanceof JsonObject)
merge((JsonObject) dest.get(e.getKey()), (JsonObject) e.getValue());
else if (e.getValue() instanceof JsonPrimitive && dest.get(e.getKey()) instanceof JsonPrimitive) {
dest.remove(e.getKey());
dest.add(e.getKey(), e.getValue());
} else
throw new Error("Not supported yet?");
} else
dest.add(e.getKey(), e.getValue());
}
}
public UnknownEntryUnion(JsonObject fields) throws SchemaViolationError {
for (Map.Entry<String, JsonElement> field : fields.entrySet()) {
String key = field.getKey();
String fieldName = getFieldName(key);
switch (fieldName) {
case "__typename": {
responseData.put(key, jsonAsString(field.getValue(), key));
break;
}
default: {
throw new SchemaViolationError(this, key, field.getValue());
}
}
}
}
/**
* Constructor.
*/
public Request(int id, String cmd, JsonObject arg) {
super("request");
this.seq = id;
this.command = cmd;
this.arguments = arg;
}
private static JsonObject buildJsonObjectRequest(String idValue, String methodValue,
JsonObject params) {
final JsonObject jsonObject = new JsonObject();
jsonObject.addProperty(ID, idValue);
jsonObject.addProperty(METHOD, methodValue);
if (params != null) {
jsonObject.add(PARAMS, params);
}
return jsonObject;
}
private String toJsonResponse(List<CdsCard> cards)
{
JsonObject ret = new JsonObject();
JsonArray cardArray = new JsonArray();
for (CdsCard card : cards)
{
cardArray.add(card.toJson());
}
ret.add("cards", cardArray);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(ret);
}
/**
* Deserializes JSON and converts it to the appropriate {@link QueryAggregation} subclass.
*
* @param json the JSON data being deserialized
* @param typeOfT the type to deserialize to, which should be {@link QueryAggregation}
* @param context additional information about the deserialization state
* @return the appropriate {@link QueryAggregation} subclass
* @throws JsonParseException signals that there has been an issue parsing the JSON
*/
@Override
public QueryAggregation deserialize(
JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
// get aggregation type from response
JsonObject jsonObject = json.getAsJsonObject();
String aggregationType = "";
for (String key : jsonObject.keySet()) {
if (key.equals(TYPE)) {
aggregationType = jsonObject.get(key).getAsString();
}
}
QueryAggregation aggregation;
if (aggregationType.equals(AggregationType.HISTOGRAM.getName())) {
aggregation = GsonSingleton.getGson().fromJson(json, Histogram.class);
} else if (aggregationType.equals(AggregationType.MAX.getName())
|| aggregationType.equals(AggregationType.MIN.getName())
|| aggregationType.equals(AggregationType.AVERAGE.getName())
|| aggregationType.equals(AggregationType.SUM.getName())
|| aggregationType.equals(AggregationType.UNIQUE_COUNT.getName())) {
aggregation = GsonSingleton.getGson().fromJson(json, Calculation.class);
} else if (aggregationType.equals(AggregationType.TERM.getName())) {
aggregation = GsonSingleton.getGson().fromJson(json, Term.class);
} else if (aggregationType.equals(AggregationType.FILTER.getName())) {
aggregation = GsonSingleton.getGson().fromJson(json, Filter.class);
} else if (aggregationType.equals(AggregationType.NESTED.getName())) {
aggregation = GsonSingleton.getGson().fromJson(json, Nested.class);
} else if (aggregationType.equals(AggregationType.TIMESLICE.getName())) {
aggregation = GsonSingleton.getGson().fromJson(json, Timeslice.class);
} else if (aggregationType.equals(AggregationType.TOP_HITS.getName())) {
aggregation = GsonSingleton.getGson().fromJson(json, TopHits.class);
} else {
aggregation = GsonSingleton.getGson().fromJson(json, GenericQueryAggregation.class);
}
return aggregation;
}
public PageWizardryStructure(Entry entry, JsonObject element) {
this.entry = entry;
if (element != null && element.has("name"))
structureName = element.getAsJsonPrimitive("name").getAsString();
if (structureName != null) {
structure = new ResourceLocation(structureName);
}
}
public Customer find(int id) throws PagarMeException {
final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET,
String.format("/%s/%s", getClassName(), id));
final Customer other = JSONUtils.getAsObject((JsonObject) request.execute(), Customer.class);
copy(other);
flush();
return other;
}
/**
* When we create a composite, operators need to create connections with the composite's input port.
* @param graph
* @param startsEndsAndOperators
* @param opDefinition
*/
@SuppressWarnings("unused")
private void fixCompositeInputNaming(JsonObject graph, List<List<JsonObject>> startsEndsAndOperators,
JsonObject opDefinition) {
// For each start
// We iterate like this because we need to also index into the operatorDefinition's inputNames list.
for(int i = 0; i < startsEndsAndOperators.get(0).size(); i++){
JsonObject start = startsEndsAndOperators.get(0).get(i);
//If the start is a source, the name doesn't need fixing.
// Only input ports that now connect to the Composite input need to be fixed.
if(start.has("config") && (hasAny(object(start, "config"), compOperatorStarts)))
continue;
// Given its output port name
// Region markers like $Parallel$ only have one input and output
String outputPortName = GsonUtilities.jstring(start.get("outputs").getAsJsonArray().get(0).getAsJsonObject(), "name");
// for each operator downstream from this start
for(JsonObject downstream : GraphUtilities.getDownstream(start, graph)){
// for each input in the downstream operator
JsonArray inputs = array(downstream, "inputs");
for(JsonElement inputObj : inputs){
JsonObject input = inputObj.getAsJsonObject();
// for each connection in that input
JsonArray connections = array(input, "connections");
for(int j = 0; j < connections.size(); j++){
// Replace the connection with the composite input port name if the
// port has a connection to the start operator.
if(connections.get(j).getAsString().equals(outputPortName)){
connections.set(j, GsonUtilities.array(opDefinition, "inputNames").get(i));
}
}
}
}
}
}
@Override
public BrewerySearchResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject object = json.getAsJsonObject();
BrewerySearchResult brewerySearchResult = new BrewerySearchResult();
brewerySearchResult.brewerId = object.get("BrewerID").getAsInt();
brewerySearchResult.brewerName = Normalizer.get().cleanHtml(object.get("BrewerName").getAsString());
brewerySearchResult.city = Normalizer.get().cleanHtml(object.get("BrewerCity").getAsString());
brewerySearchResult.countryId = object.get("CountryID").getAsInt();
if (object.has("StateID") && !(object.get("StateID") instanceof JsonNull))
brewerySearchResult.stateId = object.get("StateID").getAsInt();
return brewerySearchResult;
}
/**
* The error which occurred during class finalization, if it exists.
*
* Can return <code>null</code>.
*/
public ErrorRef getError() {
JsonObject obj = (JsonObject) json.get("error");
if (obj == null) return null;
final String type = json.get("type").getAsString();
if ("Instance".equals(type) || "@Instance".equals(type)) {
final String kind = json.get("kind").getAsString();
if ("Null".equals(kind)) return null;
}
return new ErrorRef(obj);
}
@Test
public void shouldAppendTypeFieldWhenSerializingNantTask()
{
CRTask value = nantWithPath;
JsonObject jsonObject = (JsonObject)gson.toJsonTree(value);
assertThat(jsonObject.get("type").getAsString(), is("nant"));
}
@Override
public JsonElement serialize(PayOut src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject object = SerializedTransaction.getTransactionObject(src, context);
object.add("DebitedWalletId", context.serialize(src.getDebitedWalletId()));
object.add("PaymentType", context.serialize(src.getPaymentType()));
switch (src.getMeanOfPaymentDetails().getClass().getSimpleName()) {
case "PayOutPaymentDetailsBankWire":
object.add("BankAccountId", context.serialize(((PayOutPaymentDetailsBankWire) src.getMeanOfPaymentDetails()).getBankAccountId()));
object.add("BankWireRef", context.serialize(((PayOutPaymentDetailsBankWire) src.getMeanOfPaymentDetails()).getBankWireRef()));
return object;
default:
return null;
}
}