Java 类com.google.gson.JsonObject 实例源码

项目:logviewer    文件:GistCreator.java   
/**
 * Call the API to create gist and return the http url if any
 */
private String callGistApi(String gistJson, GistListener listener) {
    try {
        CloseableHttpClient httpclient = createDefault();
        HttpPost httpPost = new HttpPost(GIST_API);
        httpPost.setHeader("Accept", "application/vnd.github.v3+json");
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setEntity(new StringEntity(gistJson, ContentType.APPLICATION_JSON));

        CloseableHttpResponse response = httpclient.execute(httpPost);

        HttpEntity responseEntity = response.getEntity();
        JsonObject result = (JsonObject) new JsonParser().parse(EntityUtils.toString(responseEntity));

        EntityUtils.consume(responseEntity);
        response.close();

        httpclient.close();
        return result.getAsJsonPrimitive("html_url").getAsString();
    } catch (Exception ex) {
    }
    return null;
}
项目:BaseClient    文件:AnimationMetadataSectionSerializer.java   
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;
    }
}
项目:gw4e.project    文件:GW4EProjectTestCase.java   
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();
    }
}
项目:filestack-java    文件:Client.java   
/**
 * 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);
}
项目:raven    文件:Notification.java   
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;
}
项目:spring-data-hana    文件:HanaDBTemplate.java   
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();
}
项目:yyox    文件:PackagePresenter.java   
/**
 * 上传包裹截图
 *
 * @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());
                    }
                }
            });
}
项目:fingerblox    文件:ImageDisplayActivity.java   
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);
}
项目:restheart-java-client    文件:RestHeartClientApi.java   
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;
}
项目:ja-micro    文件:RpcReadExceptionTest.java   
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());
    }
}
项目:backend.ai-client-java    文件:ExecutionResult.java   
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) {
    }
}
项目:graphql_java_gen    文件:GeneratedMinimal.java   
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());
            }
        }
    }
}
项目:TLIVideoConferencingv2    文件:UserSession.java   
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();
}
项目:iotgateway    文件:JsonTuples.java   
/**
     * 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;
    }
项目:raven    文件:Options.java   
@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;
}
项目:SurvivalAPI    文件:EntityDropModule.java   
@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();
}
项目:DiscordDevRant    文件:DevRant.java   
/**
 * Log in to devRant.
 *
 * @param username The username.
 * @param password The password.
 * @throws AuthenticationException If the login data is invalid.
 */
public void login(String username, char[] password) throws AuthenticationException {
    if (auth != null)
        throw new IllegalStateException("A user is already logged in.");

    JsonObject json = post(API_AUTH_TOKEN,
            new BasicNameValuePair("username", username),
            new BasicNameValuePair("password", String.valueOf(password))
    );

    // Clear the password.
    for (int i = 0; i < password.length; i++)
        password[i] = 0;

    if (!Util.jsonSuccess(json))
        throw new AuthenticationException();

    auth = Auth.fromJson(json);
}
项目:CTUConference    文件:FriendshipMessageReceiver.java   
@Override
 public void handleMessage(String messageType, JsonObject jsonMessageData, WebSocketSession session) throws IOException, Exception {
     switch(messageType) {
case "friendship.suggest":
    suggestFriendships(jsonMessageData, session);
    break;
case "friendship.request":
    requestFriendship(jsonMessageData, session);
    break;
case "friendship.accept":
             acceptFriendship(jsonMessageData, session);
             break;
case "friendship.reject":
    rejectFriendship(jsonMessageData, session);
    break;
case "friendship.leave":
    leaveFriendship(jsonMessageData, session);
    break;
     }
 }
项目:TeamNote    文件:CooperateController.java   
@RequestMapping("/getGroupChat")
@ResponseBody
public String getGroupChat(@RequestParam("notebookId") int notebookId, @RequestParam("lastChat") int lastChat) {
    UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    String username = userDetails.getUsername();
    UserInfo userInfo = userBasicService.getUserInfoByUsername(username);
    int userId = userInfo.getUserId();

    int length = cooperateService.getGroupChat(notebookId).size();
    if(lastChat == -1) lastChat = length - 1;
    String resultList = cooperateService.getGroupChatChunk(notebookId, lastChat);
    lastChat = lastChat >= 10 ? lastChat - 10 : -2;
    JsonObject json = new JsonObject();
    json.addProperty("result", resultList);
    json.addProperty("currentUser", userId);
    json.addProperty("lastChat", lastChat);
    return json.toString();
}
项目:just-ask    文件:EnrollServlet.java   
private StringEntity getJsonAsEntity(String host, int port) throws UnsupportedEncodingException {
    try {
        InputStream isr = Thread.currentThread().getContextClassLoader().getResourceAsStream("ondemand.json");
        String string = IOUtils.toString(new InputStreamReader(isr));
        JsonObject ondemand = new JsonParser().parse(string).getAsJsonObject();
        int maxSession =ConfigReader.getInstance().getMaxSession();
        JsonArray capsArray = ondemand.get("capabilities").getAsJsonArray();
        for (int i=0; i < capsArray.size(); i++) {
            capsArray.get(i).getAsJsonObject().addProperty("maxInstances", maxSession);
        }
        JsonObject configuration = ondemand.get("configuration").getAsJsonObject();
        configuration.addProperty("maxSession", maxSession);
        configuration.addProperty("hub", String.format("http://%s:%d", host, port));
        string = ondemand.toString();
        return new StringEntity(string);
    } catch (IOException e) {
        throw new GridException(e.getMessage(), e);
    }
}
项目:google-actions    文件:Oauth2Error.java   
@Override
public JsonElement serialize(Oauth2Error arg0, Type arg1, JsonSerializationContext arg2) {
    final JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("error", arg0.getError());
    jsonObject.addProperty("error_desc", arg0.getDesc());
    return jsonObject;
}
项目:BaseClient    文件:BlockFaceUV.java   
protected int parseRotation(JsonObject p_178291_1_)
{
    int i = JsonUtils.getInt(p_178291_1_, "rotation", 0);

    if (i >= 0 && i % 90 == 0 && i / 90 <= 3)
    {
        return i;
    }
    else
    {
        throw new JsonParseException("Invalid rotation " + i + " found, only 0/90/180/270 allowed");
    }
}
项目:li-android-sdk-core    文件:LiBaseResponse.java   
private List<LiBaseModel> singleEntityOrListFromJson(final JsonElement node, final String objectNamePlural,
                                                     final String objectName, final Class<? extends LiBaseModel> baseModelClass, final Gson gson) throws LiRestResponseException {
    if (node != null && node.getAsJsonObject().has(DATA)) {
        JsonObject response = node.getAsJsonObject().get(DATA).getAsJsonObject();
        if (!response.has(TYPE)) {
            throw LiRestResponseException.jsonSerializationError("Required data type not found in response");
        }

        String type = response.get(TYPE).getAsString();
        if (!type.equalsIgnoreCase(objectName) && !type.equalsIgnoreCase(objectNamePlural)) {
            throw LiRestResponseException.illegalArgumentError("Required object type not found in response");
        }

        if (type.equalsIgnoreCase(objectNamePlural) && response.get(ITEMS).isJsonArray()) {
            JsonArray jsonArray = response.get(ITEMS).getAsJsonArray();
            List<LiBaseModel> elementList = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JsonObject element = jsonArray.get(i).getAsJsonObject();
                try {
                    elementList.add(gson.fromJson(element, baseModelClass));
                } catch (IllegalStateException | JsonSyntaxException exception) {
                    throw LiRestResponseException.jsonSerializationError("Bad json response:" + exception.getMessage());
                }
            }
            return elementList;
        } else if (type.equalsIgnoreCase(objectName) && response.get(ITEM).isJsonObject()) {
            final List<LiBaseModel> objects = new ArrayList<>();
            objects.add(gson.fromJson(response.get(ITEM).getAsJsonObject(), baseModelClass));
            return objects;
        } else {
            throw LiRestResponseException.jsonSerializationError("Unable to parse " + objectName + " or " +
                    objectNamePlural + " from json:" + node);
        }
    } else {
        throw LiRestResponseException.jsonSerializationError("Server Error. Please check logs");
    }
}
项目:civify-app    文件:AchievementAdapterImplTest.java   
@Test
public void testInvalidGetAchievements() {
    JsonObject body = new JsonObject();
    body.addProperty("message", "Doesn’t exists record");
    MockResponse mockResponse = new MockResponse()
            .setResponseCode(HttpURLConnection.HTTP_NOT_FOUND)
            .setBody(body.toString());
    mMockWebServer.enqueue(mockResponse);
    ListAchievementsSimpleCallback mockCallback = mock(ListAchievementsSimpleCallback.class);

    mAchievementAdapter.getAchievements(mockCallback);

    verify(mockCallback, timeout(1000)).onFailure();
}
项目:easyprefs    文件:MorePrefs.java   
@Override
public String put(JsonObject jsonObject) {
    if (jsonObject == null) {
        return null;
    }
    return jsonObject.toString();
}
项目:filestack-java    文件:FileLink.java   
/**
 * Determines if an image FileLink is "safe for work" using the Google Vision API.
 *
 * @throws HttpException on error response from backend
 * @throws IOException           on network failure
 *
 * @see <a href="https://www.filestack.com/docs/tagging"></a>
 */
public boolean imageSfw() throws IOException {
  if (!config.hasSecurity()) {
    throw new IllegalStateException("Security must be set in order to tag an image");
  }

  ImageTransform transform = new ImageTransform(config, handle, false);
  transform.addTask(new ImageTransformTask("sfw"));
  JsonObject json = transform.getContentJson();

  return json.get("sfw").getAsBoolean();
}
项目:buckaroo    文件:DependencyGroupSerializer.java   
@Override
public JsonElement serialize(final DependencyGroup dependencyGroup, final Type type, final JsonSerializationContext context) {

    Preconditions.checkNotNull(dependencyGroup);
    Preconditions.checkNotNull(type);
    Preconditions.checkNotNull(context);

    final JsonObject jsonObject = new JsonObject();

    for (final Dependency i : dependencyGroup.entries()) {
        jsonObject.addProperty(i.project.encode(), i.requirement.encode());
    }

    return jsonObject;
}
项目:ULCRS    文件:DataParse.java   
/**
 * Parse courses. This depends on shifts.
 *
 * @param input - JsonObject response from ULC to parse into ULCRS data.
 * @param shifts - HashMap of shifts for easy lookup for already-parsed shifts.
 * @return HashMap - return HashMap of id:course for courses parsed from input.
 */
private static HashMap<Integer, Course> parseCourses(JsonObject input, HashMap<Integer, Shift> shifts) {
    // Get course JsonArray from JsonObject
    JsonArray coursesJson = input.get(COURSES_KEY).getAsJsonArray();
    JsonArray courseRequirementsJson = input.get(COURSE_REQUIREMENTS_KEY).getAsJsonArray();

    List<ULCCourse> ulcCourses = new Gson().fromJson(coursesJson, new TypeToken<List<ULCCourse>>() {
    }.getType());
    List<ULCCourseRequirements> ulcCourseRequirementsList = new Gson().fromJson(courseRequirementsJson, new TypeToken<List<ULCCourseRequirements>>() {
    }.getType());

    // Map course id to ULCCourseRequirements object for that course
    Map<Integer, ULCCourseRequirements> courseIdToULCCourseRequirements = ulcCourseRequirementsList.stream()
            .collect(Collectors.toMap(ULCCourseRequirements::getCourseId, item -> item));

    // Transform json courses into Course objects
    HashMap<Integer, Course> courses = new HashMap<>();
    ulcCourses.forEach(ulcCourse -> {
        ULCCourseRequirements ulcCourseRequirement = courseIdToULCCourseRequirements.get(ulcCourse.getId());
        if (ulcCourseRequirement != null) {
            CourseRequirements courseRequirement = ulcCourseRequirement.toCourseRequirements(shifts);
            Course course = ulcCourse.toCourse(courseRequirement);
            courses.put(course.getId(), course);
        }
    });

    return courses;
}
项目:cyp2sql    文件:CypherTranslator.java   
/**
 * Takes token list of JSON based properties string, and converts this to an actual JSON object.
 *
 * @param propsString Token list in form similar to ["{", "key", ":", "value", "}"]
 * @return JSONObject matching the propsString argument.
 */
private static JsonObject getJSONProps(List<String> propsString) {
    StringBuilder json = new StringBuilder();
    json.append("{");

    boolean listSyntax = propsString.contains("[");

    int i = 0;

    for (String a : propsString) {
        if (a.equals(",")) {
            continue;
        } else if (a.equals("[")) {
            json.append("[");
            continue;
        } else if (a.equals("]")) {
            json.setLength(json.length() - 2);
            json.append("]").append(", ");
        } else if (i % 3 == 0) {
            json.append("\"").append(a).append("\"");
        } else if (i % 3 == 1) {
            json.append(":");
        } else if (i % 3 == 2) {
            json.append(a).append(", ");
            if (listSyntax) continue;
        }
        i++;
    }

    // remove trailing comma
    json.setLength(json.length() - 2);
    json.append("}");
    return parser.parse(json.toString()).getAsJsonObject();
}
项目:TextDisplayer    文件:Message.java   
public Message(JsonObject object) {
    this.name = object.has("name") ? object.get("name").getAsString() : MessageHelper.getRandomString(20);
    this.message = object.has("message") && !object.get("message").getAsString().isEmpty() ? object.get("message").getAsString() : "unknown";
    this.isChroma = object.has("usechroma") && object.get("usechroma").getAsBoolean();
    this.useShadow = object.has("useshadow") && object.get("useshadow").getAsBoolean();
    this.a = object.has("a") && object.get("a").getAsBoolean();
    this.b = !object.has("b") || object.get("b").getAsBoolean();
    this.c = !object.has("c") || object.get("c").getAsBoolean();
    this.scale = object.has("scale") ? MessageHelper.cap(object.get("scale").getAsFloat(), 1, 2) : 1;
    this.x = object.has("x") ? object.get("x").getAsInt() : 0;
    this.y = object.has("y") ? object.get("y").getAsInt() : 0;

    this.fileLocation = TextDisplayerMod.getInstance().getLoader().getMainDir().getPath() + "\\" + formatName(this.name).toLowerCase() + ".info";
}
项目:gcp    文件:Spark8Organized.java   
private static PairFunction<Tuple2<String, ExampleXML>, Object, JsonObject> prepToBq() {
  return tuple -> {
    JsonObject json = new JsonObject();
    json.addProperty("property1", tuple._2().getProperty1());
    json.addProperty("insertId", tuple._1());
    return new Tuple2<>(null, json);
  };
}
项目:pnc-repressurized    文件:AmadronOfferSettings.java   
@Override
protected void readFromJson(JsonObject json) {
    maxTradesPerPlayer = json.get("maxTradesPerPlayer").getAsInt();
    notifyOfTradeAddition = json.get("notifyOfTradeAddition").getAsBoolean();
    notifyOfTradeRemoval = json.get("notifyOfTradeRemoval").getAsBoolean();
    notifyOfDealMade = json.get("notifyOfDealMade").getAsBoolean();
}
项目:ultimate-geojson    文件:FeatureDeserializer.java   
@Override
public FeatureDto deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {

    FeatureDto dto = new FeatureDto();

    JsonObject asJsonObject = json.getAsJsonObject();
    JsonElement geometryElement = asJsonObject.get("geometry");
    if (geometryElement != null) {
        String typeOfGeometry = geometryElement.getAsJsonObject().get("type").getAsString();
        GeoJSONObjectTypeEnum typeEnum = GeoJSONObjectTypeEnum.valueOf(typeOfGeometry);
        GeometryDto geometryDto = context.deserialize(geometryElement, typeEnum.getDtoClass());
        dto.setGeometry(geometryDto);

    }

    JsonElement propertiesJsonElement = asJsonObject.get("properties");
    if (propertiesJsonElement != null) {
        dto.setProperties(propertiesJsonElement.toString());
    }

    JsonElement idJsonElement = asJsonObject.get("id");
    if (idJsonElement != null) {
        dto.setId(idJsonElement.getAsString());
    }

    dto.setBbox(BoundingBoxParser.parseBbox(asJsonObject, context));

    return dto;
}
项目:bStats-Metrics    文件:Metrics.java   
@Override
public JsonObject getChartData() throws Exception {
    JsonObject data = new JsonObject();
    JsonObject values = new JsonObject();
    Map<String, Map<String, Integer>> map = callable.call();
    if (map == null || map.isEmpty()) {
        // Null = skip the chart
        return null;
    }
    boolean reallyAllSkipped = true;
    for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
        JsonObject value = new JsonObject();
        boolean allSkipped = true;
        for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {
            value.addProperty(valueEntry.getKey(), valueEntry.getValue());
            allSkipped = false;
        }
        if (!allSkipped) {
            reallyAllSkipped = false;
            values.add(entryValues.getKey(), value);
        }
    }
    if (reallyAllSkipped) {
        // Null = skip the chart
        return null;
    }
    data.add("values", values);
    return data;
}
项目:BaseClient    文件:ItemTransformVec3f.java   
private Vector3f parseVector3f(JsonObject jsonObject, String key, Vector3f defaultValue)
{
    if (!jsonObject.has(key))
    {
        return defaultValue;
    }
    else
    {
        JsonArray jsonarray = JsonUtils.getJsonArray(jsonObject, key);

        if (jsonarray.size() != 3)
        {
            throw new JsonParseException("Expected 3 " + key + " values, found: " + jsonarray.size());
        }
        else
        {
            float[] afloat = new float[3];

            for (int i = 0; i < afloat.length; ++i)
            {
                afloat[i] = JsonUtils.getFloat(jsonarray.get(i), key + "[" + i + "]");
            }

            return new Vector3f(afloat[0], afloat[1], afloat[2]);
        }
    }
}
项目:civify-app    文件:EventAdapterImplTest.java   
@Test
public void testInvalidGetAchievement() {
    JsonObject body = new JsonObject();
    body.addProperty("message", "Doesn’t exists record");
    MockResponse mockResponse = new MockResponse()
            .setResponseCode(HttpURLConnection.HTTP_NOT_FOUND)
            .setBody(body.toString());
    mMockWebServer.enqueue(mockResponse);
    EventSimpleCallback mockCallback = mock(EventSimpleCallback.class);

    mEventAdapter.getEvent(mEvent.getToken(), mockCallback);

    verify(mockCallback, timeout(1000)).onFailure();
}
项目:skywalking-mock-collector    文件:ValidateDataSerializer.java   
@Override
public JsonElement serialize(ValidateData src, Type typeOfSrc, JsonSerializationContext context) {
    Gson gson = new GsonBuilder().registerTypeAdapter(RegistryItem.class, new RegistryItemSerializer())
        .registerTypeAdapter(SegmentItems.class, new SegmentItemsSerializer()).create();

    JsonObject jsonObject = new JsonObject();
    jsonObject.add("registryItems", gson.toJsonTree(src.getRegistryItem()));
    jsonObject.add("segmentItems", gson.toJsonTree(src.getSegmentItem()));
    return jsonObject;
}
项目:BaseClient    文件:BlockFaceUV.java   
private float[] parseUV(JsonObject p_178292_1_)
{
    if (!p_178292_1_.has("uv"))
    {
        return null;
    }
    else
    {
        JsonArray jsonarray = JsonUtils.getJsonArray(p_178292_1_, "uv");

        if (jsonarray.size() != 4)
        {
            throw new JsonParseException("Expected 4 uv values, found: " + jsonarray.size());
        }
        else
        {
            float[] afloat = new float[4];

            for (int i = 0; i < afloat.length; ++i)
            {
                afloat[i] = JsonUtils.getFloat(jsonarray.get(i), "uv[" + i + "]");
            }

            return afloat;
        }
    }
}
项目:Phoenix-for-VK    文件:AttachmentsEntryDtoAdapter.java   
private VKApiAttachment parse(String type, JsonObject root, JsonDeserializationContext context){
    JsonElement o = root.get(type);

    //{"type":"photos_list","photos_list":["406536042_456239026"]}

    if (VkApiAttachments.TYPE_PHOTO.equals(type)) {
        return context.deserialize(o, VKApiPhoto.class);
    } else if (VkApiAttachments.TYPE_VIDEO.equals(type)) {
        return context.deserialize(o, VKApiVideo.class);
    } else if (VkApiAttachments.TYPE_AUDIO.equals(type)) {
        return context.deserialize(o, VKApiAudio.class);
    } else if (VkApiAttachments.TYPE_DOC.equals(type)) {
        return context.deserialize(o, VkApiDoc.class);
    } else if (VkApiAttachments.TYPE_POST.equals(type)) {
        return context.deserialize(o, VKApiPost.class);
        //} else if (VkApiAttachments.TYPE_POSTED_PHOTO.equals(type)) {
        //    return context.deserialize(o, VKApiPostedPhoto.class);
    } else if (VkApiAttachments.TYPE_LINK.equals(type)) {
        return context.deserialize(o, VKApiLink.class);
        //} else if (VkApiAttachments.TYPE_NOTE.equals(type)) {
        //    return context.deserialize(o, VKApiNote.class);
        //} else if (VkApiAttachments.TYPE_APP.equals(type)) {
        //    return context.deserialize(o, VKApiApplicationContent.class);
    } else if (VkApiAttachments.TYPE_POLL.equals(type)) {
        return context.deserialize(o, VKApiPoll.class);
    } else if (VkApiAttachments.TYPE_WIKI_PAGE.equals(type)) {
        return context.deserialize(o, VKApiWikiPage.class);
    } else if (VkApiAttachments.TYPE_ALBUM.equals(type)) {
        return context.deserialize(o, VKApiPhotoAlbum.class);
    } else if (VkApiAttachments.TYPE_STICKER.equals(type)) {
        return context.deserialize(o, VKApiSticker.class);
    }

    return null;
}
项目:DecompiledMinecraft    文件:ModelBlockDefinition.java   
protected List<ModelBlockDefinition.Variants> parseVariantsList(JsonDeserializationContext p_178334_1_, JsonObject p_178334_2_)
{
    JsonObject jsonobject = JsonUtils.getJsonObject(p_178334_2_, "variants");
    List<ModelBlockDefinition.Variants> list = Lists.<ModelBlockDefinition.Variants>newArrayList();

    for (Entry<String, JsonElement> entry : jsonobject.entrySet())
    {
        list.add(this.parseVariants(p_178334_1_, entry));
    }

    return list;
}