当前位置: 首页>>代码示例>>Java>>正文


Java JsonObject类代码示例

本文整理汇总了Java中com.google.gson.JsonObject的典型用法代码示例。如果您正苦于以下问题:Java JsonObject类的具体用法?Java JsonObject怎么用?Java JsonObject使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


JsonObject类属于com.google.gson包,在下文中一共展示了JsonObject类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: keypointsToJSON

import com.google.gson.JsonObject; //导入依赖的package包/类
public String keypointsToJSON(MatOfKeyPoint kps){
    Gson gson = new Gson();

    JsonArray jsonArr = new JsonArray();

    KeyPoint[] kpsArray = kps.toArray();
    for(KeyPoint kp : kpsArray){
        JsonObject obj = new JsonObject();

        obj.addProperty("class_id", kp.class_id);
        obj.addProperty("x", kp.pt.x);
        obj.addProperty("y", kp.pt.y);
        obj.addProperty("size", kp.size);
        obj.addProperty("angle", kp.angle);
        obj.addProperty("octave", kp.octave);
        obj.addProperty("response", kp.response);

        jsonArr.add(obj);
    }

    return gson.toJson(jsonArr);
}
 
开发者ID:jorenham,项目名称:fingerblox,代码行数:23,代码来源:ImageDisplayActivity.java

示例2: getCloudItems

import com.google.gson.JsonObject; //导入依赖的package包/类
/**
 * Gets contents of a user's cloud "drive". If the user has not authorized for the provider, the
 * response will contain an OAuth URL that should be opened in a browser.
 *
 * @param providerName one of the static CLOUD constants in this class
 * @param next         pagination token returned in previous response
 *
 * @throws HttpException on error response from backend
 * @throws IOException           on network failure
 */
@SuppressWarnings("ConstantConditions")
public CloudResponse getCloudItems(String providerName, String path, String next)
    throws IOException {

  JsonObject params = makeCloudParams(providerName, path, next);
  Response<JsonObject> response = Networking.getCloudService().list(params).execute();
  Util.checkResponseAndThrow(response);
  JsonObject base = response.body();

  if (base.has("token")) {
    sessionToken = base.get("token").getAsString();
  }

  JsonElement provider = base.get(providerName);
  Gson gson = new Gson();
  return gson.fromJson(provider, CloudResponse.class);
}
 
开发者ID:filestack,项目名称:filestack-java,代码行数:28,代码来源:Client.java

示例3: parseAnimationFrame

import com.google.gson.JsonObject; //导入依赖的package包/类
private AnimationFrame parseAnimationFrame(int p_110492_1_, JsonElement p_110492_2_)
{
    if (p_110492_2_.isJsonPrimitive())
    {
        return new AnimationFrame(JsonUtils.getInt(p_110492_2_, "frames[" + p_110492_1_ + "]"));
    }
    else if (p_110492_2_.isJsonObject())
    {
        JsonObject jsonobject = JsonUtils.getJsonObject(p_110492_2_, "frames[" + p_110492_1_ + "]");
        int i = JsonUtils.getInt(jsonobject, "time", -1);

        if (jsonobject.has("time"))
        {
            Validate.inclusiveBetween(1L, 2147483647L, (long)i, "Invalid frame time");
        }

        int j = JsonUtils.getInt(jsonobject, "index");
        Validate.inclusiveBetween(0L, 2147483647L, (long)j, "Invalid frame index");
        return new AnimationFrame(j, i);
    }
    else
    {
        return null;
    }
}
 
开发者ID:SkidJava,项目名称:BaseClient,代码行数:26,代码来源:AnimationMetadataSectionSerializer.java

示例4: assertFileInCache

import com.google.gson.JsonObject; //导入依赖的package包/类
private void assertFileInCache (File file,String key) throws IOException {
	 InputStream in = new FileInputStream(file);
	 try {
		Reader reader = new InputStreamReader(in);
		String text = CharStreams.toString(reader);
		JsonParser jp = new JsonParser();
		JsonElement je = jp.parse(text);
		JsonObject jsonCache = je.getAsJsonObject();
		JsonElement elt = jsonCache.get(key);
		JsonObject generatedObj = elt.getAsJsonObject();
		boolean generated = generatedObj.get("generated").getAsBoolean();
		assertTrue("Test not generated", generated);
	} finally {
		if (in!=null) in.close();
	}
}
 
开发者ID:gw4e,项目名称:gw4e.project,代码行数:17,代码来源:GW4EProjectTestCase.java

示例5: toJSON

import com.google.gson.JsonObject; //导入依赖的package包/类
public JsonElement toJSON() {
    JsonObject json = new JsonObject();
    if (null != alert) {
        if(alert instanceof JsonObject) {
            json.add(PlatformNotification.ALERT, (JsonObject) alert);
        } else if (alert instanceof IosAlert) {
            json.add(PlatformNotification.ALERT, ((IosAlert) alert).toJSON());
        } else {
            json.add(PlatformNotification.ALERT, new JsonPrimitive(alert.toString()));
        }
    }
    if (null != notifications) {
        for (PlatformNotification pn : notifications) {
            if (this.alert != null && pn.getAlert() == null) {
                pn.setAlert(this.alert);
            }
            
            Preconditions.checkArgument(! (null == pn.getAlert()),
                    "For any platform notification, alert field is needed. It can be empty string.");

            json.add(pn.getPlatform(), pn.toJSON());
        }
    }
    return json;
}
 
开发者ID:marlonwang,项目名称:raven,代码行数:26,代码来源:Notification.java

示例6: HanaDBTemplate

import com.google.gson.JsonObject; //导入依赖的package包/类
public HanaDBTemplate() {
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Point.class, (JsonSerializer<Point>) (Point src, Type type, JsonSerializationContext context) -> {
        JsonObject obj = new JsonObject();
        // serialize it all to strings for reasons..
        obj.addProperty("ZEITREIHE", src.getTimeseries());
        obj.addProperty("TIME", String.valueOf(src.getTimestamp()));
        obj.addProperty("VALUE", src.getValue().toString());
        return obj;
    });
    gson = builder.create();

    OkHttpClient.Builder okHBuilder = new OkHttpClient.Builder();
    okHBuilder.readTimeout(30, TimeUnit.SECONDS);
    okHBuilder.writeTimeout(30, TimeUnit.SECONDS);
    okHttpClient = okHBuilder.build();
}
 
开发者ID:NEMAR,项目名称:spring-data-hana,代码行数:18,代码来源:HanaDBTemplate.java

示例7: putPackageImage

import com.google.gson.JsonObject; //导入依赖的package包/类
/**
 * 上传包裹截图
 *
 * @param mImage1
 * @param mImage2
 * @param mImage3
 */
public void putPackageImage(String mImage1, String mImage2, String mImage3) {

    mModel.putPackageImage(mImage1, mImage2, mImage3)
            .subscribeOn(Schedulers.io())
            .retryWhen(new RetryWithDelay(3, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
            .subscribeOn(AndroidSchedulers.mainThread())
            .observeOn(AndroidSchedulers.mainThread())
            .compose(RxUtils.<BaseJson<JsonObject>>bindToLifecycle(mRootView))//使用RXlifecycle,使subscription和activity一起销毁
            .subscribe(new ErrorHandleSubscriber<BaseJson<JsonObject>>(mErrorHandler) {

                @Override
                public void onNext(BaseJson<JsonObject> jsonObjectBaseJson) {
                    if (jsonObjectBaseJson.getStatus() == 0) {
                        mRootView.packageImage(jsonObjectBaseJson.getStatus());
                    } else {
                        mRootView.showMessage(jsonObjectBaseJson.getMsgs());
                        mRootView.packageImage(jsonObjectBaseJson.getStatus());
                    }
                }
            });
}
 
开发者ID:Zyj163,项目名称:yyox,代码行数:29,代码来源:PackagePresenter.java

示例8: extractFromResponse

import com.google.gson.JsonObject; //导入依赖的package包/类
private RestHeartClientResponse extractFromResponse(final CloseableHttpResponse httpResponse) {
    RestHeartClientResponse response = null;
    JsonObject responseObj = null;
    if (httpResponse != null) {
        StatusLine statusLine = httpResponse.getStatusLine();
        Header[] allHeaders = httpResponse.getAllHeaders();
        HttpEntity resEntity = httpResponse.getEntity();
        if (resEntity != null) {
            try {
                String responseStr = IOUtils.toString(resEntity.getContent(), "UTF-8");
                if (responseStr != null && !responseStr.isEmpty()) {
                    JsonParser parser = new JsonParser();
                    responseObj = parser.parse(responseStr).getAsJsonObject();
                }
            } catch (IOException e) {
                LOGGER.log(Level.SEVERE, "Was unable to extract response body", e);
            }
        }

        response = new RestHeartClientResponse(statusLine, allHeaders, responseObj);
    }
    return response;
}
 
开发者ID:SoftGorilla,项目名称:restheart-java-client,代码行数:24,代码来源:RestHeartClientApi.java

示例9: testBodyReading

import com.google.gson.JsonObject; //导入依赖的package包/类
public void testBodyReading(String first, String second) throws IOException {
    ServletInputStream x = (ServletInputStream) new RpcHandlerTest_InputStream(second);
    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    Map<String, Set<String>> headers = new TreeMap<>();
    when(request.getHeaderNames())
            .thenReturn(
                    new RpcReadExceptionTest.RpcHandlerTest_IteratorEnumeration<>(headers.keySet().iterator())
            );

    when(request.getInputStream()).thenReturn(x);
    when(request.getRequestURL())
            .thenReturn(new StringBuffer("http://fizz.buzz"));

    RpcReadException rpcReadException = new RpcReadException(first.getBytes(), x, "i am a message");
    String json = rpcReadException.toJson(request);

    try {
        JsonElement root = new JsonParser().parse(json);
        JsonObject jsob = root.getAsJsonObject();
        JsonElement b = jsob.get("request_body");
        Assert.assertNotNull(b);
        Assert.assertEquals(first+second, this.decode(b.getAsString()));
    } catch (Exception ex) {
        Assert.fail(ex.toString());
    }
}
 
开发者ID:Sixt,项目名称:ja-micro,代码行数:27,代码来源:RpcReadExceptionTest.java

示例10: ExecutionResult

import com.google.gson.JsonObject; //导入依赖的package包/类
public ExecutionResult(JsonObject jsonResult) {
    this.jsonResult = jsonResult;
    try {
        JsonObject result = jsonResult.get("result").getAsJsonObject();
        JsonArray console = result.get("console").getAsJsonArray();
        this.status = RunStatus.get(result.get("status").getAsString());
        for (int i = 0; i < console.size(); i++) {
            JsonArray a = console.get(i).getAsJsonArray();
            String type = a.get(0).getAsString();
            if(type.equals("stdout")) {
                this.stdout = a.get(1).getAsString();
            } else if (type.equals("stderr")) {
                this.stderr = a.get(1).getAsString();
            }
        }
    } catch (NullPointerException e) {
    }
}
 
开发者ID:lablup,项目名称:backend.ai-client-java,代码行数:19,代码来源:ExecutionResult.java

示例11: QueryRoot

import com.google.gson.JsonObject; //导入依赖的package包/类
public QueryRoot(JsonObject fields) throws SchemaViolationError {
    for (Map.Entry<String, JsonElement> field : fields.entrySet()) {
        String key = field.getKey();
        String fieldName = getFieldName(key);
        switch (fieldName) {
            case "version": {
                String optional1 = null;
                if (!field.getValue().isJsonNull()) {
                    optional1 = jsonAsString(field.getValue(), key);
                }

                responseData.put(key, optional1);

                break;
            }

            case "__typename": {
                responseData.put(key, jsonAsString(field.getValue(), key));
                break;
            }
            default: {
                throw new SchemaViolationError(this, key, field.getValue());
            }
        }
    }
}
 
开发者ID:Shopify,项目名称:graphql_java_gen,代码行数:27,代码来源:GeneratedMinimal.java

示例12: receiveVideoFrom

import com.google.gson.JsonObject; //导入依赖的package包/类
public void receiveVideoFrom(UserSession sender, String sdpOffer) throws IOException {
  log.info("USER {}: connecting with {} in room {}", this.name, sender.getName(), this.roomName);

  log.trace("USER {}: SdpOffer for {} is {}", this.name, sender.getName(), sdpOffer);

  final String ipSdpAnswer = this.getEndpointForUser(sender).processOffer(sdpOffer);
  final JsonObject scParams = new JsonObject();
  scParams.addProperty("id", "receiveVideoAnswer");
  scParams.addProperty("name", sender.getName());
  scParams.addProperty("sdpAnswer", ipSdpAnswer);

  log.trace("USER {}: SdpAnswer for {} is {}", this.name, sender.getName(), ipSdpAnswer);
  this.sendMessage(scParams);
  log.debug("gather candidates");
  this.getEndpointForUser(sender).gatherCandidates();
}
 
开发者ID:jake-kent,项目名称:TLIVideoConferencingv2,代码行数:17,代码来源:UserSession.java

示例13: wrap

import com.google.gson.JsonObject; //导入依赖的package包/类
/**
     * Create a JsonObject wrapping a raw {@code Pair<Long msec,T reading>>} sample.
     * @param <T> Tuple type
     * @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;
    }
 
开发者ID:osswangxining,项目名称:iotgateway,代码行数:31,代码来源:JsonTuples.java

示例14: toJSON

import com.google.gson.JsonObject; //导入依赖的package包/类
@Override
public JsonElement toJSON() {
    JsonObject json = new JsonObject();
    if (sendno > 0) {
        json.add(SENDNO, new JsonPrimitive(sendno));
    }
    if (overrideMsgId > 0) {
        json.add(OVERRIDE_MSG_ID, new JsonPrimitive(overrideMsgId));
    }
    if (timeToLive >= 0) {
        json.add(TIME_TO_LIVE, new JsonPrimitive(timeToLive));
    }
    
    json.add(APNS_PRODUCTION, new JsonPrimitive(apnsProduction));
    
    if (bigPushDuration > 0) {
    	json.add(BIG_PUSH_DURATION,  new JsonPrimitive(bigPushDuration));
    }
    
    return json;
}
 
开发者ID:marlonwang,项目名称:raven,代码行数:22,代码来源:Options.java

示例15: buildFromJson

import com.google.gson.JsonObject; //导入依赖的package包/类
@Override
public Map<String, Object> buildFromJson(Map<String, JsonElement> configuration) throws Exception
{
    if (configuration.containsKey("drops"))
    {
        JsonArray dropsJson = configuration.get("drops").getAsJsonArray();

        for (int i = 0; i < dropsJson.size(); i++)
        {
            JsonObject dropJson = dropsJson.get(i).getAsJsonObject();

            EntityType entityType = EntityType.valueOf(dropJson.get("entity").getAsString().toUpperCase());
            JsonArray stacksJson = dropJson.get("stacks").getAsJsonArray();
            ItemStack[] stacks = new ItemStack[stacksJson.size()];

            for (int j = 0; j < stacksJson.size(); j++)
                stacks[j] = ItemUtils.strToStack(stacksJson.get(i).getAsString());

            this.addCustomDrops(entityType, stacks);
        }
    }

    return this.build();
}
 
开发者ID:SamaGames,项目名称:SurvivalAPI,代码行数:25,代码来源:EntityDropModule.java


注:本文中的com.google.gson.JsonObject类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。