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

项目:graphflow    文件:Filter.java   
@Override
public JsonObject toJson() {
    JsonObject jsonFilter = new JsonObject();

    JsonArray jsonPropertyPredicates = new JsonArray();
    for (QueryPredicate queryPredicate : queryPredicates) {
        jsonPropertyPredicates.add(queryPredicate.toJson());
    }
    JsonArray jsonArguments = new JsonArray();
    JsonObject jsonArgument = new JsonObject();
    jsonArgument.addProperty(JsonKeyConstants.NAME.toString(), "Vertex Indices");
    jsonArgument.add(JsonKeyConstants.VALUE.toString(), jsonPropertyPredicates);
    jsonArguments.add(jsonArgument);
    jsonFilter.addProperty(JsonKeyConstants.NAME.toString(), "Filter (σ)");
    jsonFilter.add(JsonKeyConstants.ARGS.toString(), jsonArguments);

    return jsonFilter;
}
项目:ultimate-geojson    文件:GeometryCollectionDeserializer.java   
@Override
public GeometryCollectionDto deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {

    GeometryCollectionDto dto = new GeometryCollectionDto();
    List<GeometryDto> geometries = new ArrayList<>();
    dto.setGeometries(geometries);

    JsonObject asJsonObject = json.getAsJsonObject();
    JsonArray jsonArray = asJsonObject.get("geometries").getAsJsonArray();
    if (jsonArray == null) {
        return dto;
    }

    for (int i = 0; i < jsonArray.size(); i++) {
        JsonObject geometryElement = jsonArray.get(i).getAsJsonObject();
        String typeOfGeometry = geometryElement.get("type").getAsString();
        GeoJSONObjectTypeEnum typeEnum = GeoJSONObjectTypeEnum.valueOf(typeOfGeometry);

        GeometryDto geometryDto = context.deserialize(geometryElement, typeEnum.getDtoClass());
        geometries.add(geometryDto);
    }

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

    return dto;
}
项目:SOS-The-Healthcare-Companion    文件:InsertQuery.java   
public Call<InsertResult<R>, DBException> build() {
    /* Create the query object */
    this.insObjs.add(this.currentObj);
    JsonObject query = new JsonObject();
    query.add("objects", this.insObjs);
    JsonArray retArr = new JsonArray();
    for (String retCol : this.retSet)
        retArr.add(new JsonPrimitive(retCol));
    query.add("returning", retArr);

    String opUrl = "/table/" + table.getTableName() + "/insert";

    Converter<InsertResult<R>, DBException> converter
            = new DBResponseConverter<>(table.getInsResType());
    return db.mkCall(opUrl, db.gson.toJson(query), converter);
}
项目:gremzeppelin    文件:GremlinInterpreter.java   
@Override
public InterpreterResult interpret(String gremlin, InterpreterContext interpreterContext) {
    logger.info("execute gremlin traversal {}", gremlin);
    try {
        ResultSet results = client.submit(gremlin);
        JsonArray array = results.stream()
                                 .map(result -> new JsonPrimitive(results.toString()))
                                 .collect(JsonArray::new, JsonArray::add, JsonArray::addAll);

        //TODO extract ResultSet
        //Case MessageSerializer

        return new InterpreterResult(InterpreterResult.Code.SUCCESS, array.toString());
    } catch (RuntimeException e) {
        return new InterpreterResult(InterpreterResult.Code.ERROR, e.getMessage());
    }
}
项目:newblog    文件:TagServiceImpl.java   
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public Integer updatetag(Integer tId) {
    //标签
    List<Tag> tags = tagMapper.getAllTags();
    JsonArray jsonArray = new JsonArray();
    for (Tag tag : tags) {
        List<Blog> blogs = tagMapper.getblogbytagid(tag.gettId());
        String str = tag.gettName() + " " + "(" + String.valueOf(blogs.size()) + ")";
        KeyAndValue keyAndValue = new KeyAndValue();
        keyAndValue.setKey(tag.gettName());
        keyAndValue.setValue(str);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("key", tag.gettId());
        jsonObject.addProperty("value", str);
        jsonArray.add(jsonObject);
    }
    boolean result = redisTemplate.execute((RedisCallback<Boolean>) connection -> {
        RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
        connection.set(serializer.serialize("biaoqian"), serializer.serialize(jsonArray.toString()));
        return true;
    });
    return tId;
}
项目:Hub    文件:GraouManager.java   
@Override
public void loadConfiguration(JsonArray rootJson)
{
    if (rootJson.size() == 0)
        return;

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

        Location catLocation = LocationUtils.str2loc(graouJson.get("cat").getAsString());
        Location doorLocation = LocationUtils.str2loc(graouJson.get("door").getAsString());
        Location treasureLocation = LocationUtils.str2loc(graouJson.get("treasure").getAsString());
        Location openingLocation = LocationUtils.str2loc(graouJson.get("opening").getAsString());

        Graou graou = new Graou(this.hub, catLocation, doorLocation, treasureLocation, openingLocation);

        this.interactions.add(graou);
        this.log(Level.INFO, "Registered Graou at '" + graouJson.get("cat").getAsString());
    }
}
项目:ja-micro    文件:RegistrationManagerTest.java   
@Test
public void verifyRegistrationTags() throws IOException {
    JsonObject json = manager.buildJsonRequest();
    JsonArray tags = (JsonArray) json.get("Tags");
    assertThat(tags).hasSize(7);
    assertThat(tags).contains(new JsonPrimitive(
            "t-789cab562aa92c4855b2522acdcbcecb2fcf53aa05003d1c068d"));
    assertThat(tags).contains(new JsonPrimitive(
            "t-789cab562a294acc2b2ec82f2a51b252ca28292950aa05004f930768"));
    assertThat(tags).contains(new JsonPrimitive(
            "t-789cab564a2acacf4e2d52b252ca28292950aa0500364d0600"));
    assertThat(tags).contains(new JsonPrimitive(
            "t-789cab562a4e2d2a4b2d52b2522a2a4856aa050030dd0597"));
    assertThat(tags).contains(new JsonPrimitive(
            "t-789cab562a4a4dcf2c2e29aa54b2524acecf2b2ecd51aa0500560f07c8"));
    assertThat(tags).contains(new JsonPrimitive(
            "v-789c33d033d033d04d83000016c103e4"));
    assertThat(tags).contains(new JsonPrimitive("e-789cc58fbb0e02211045ff656a4a63c167d81" +
            "a63461957121eeb001bcd867f179275616d2ced269739c3b93338b4041222850802981ea94e" +
            "72fe3c1c9644407c8ddb6042532690c77539104ffa4a674bf1ee55634264ed860e71c9982c3" +
            "aaedc740574c95e881b78d34f52fbdd3779ca55358cde05dab82e5127bb26ffb36d24317bfe" +
            "f5512d57945061c45aae6c11da7a1e4d6992f31bda579619"));
}
项目: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);
}
项目:Randores2    文件:RandoresForgeUpgradeRecipeFactory.java   
@Override
public IRecipe parse(JsonContext context, JsonObject json) {
    int clamp = JsonUtils.getInt(json, "clamp");
    boolean combining = JsonUtils.getBoolean(json, "combining");

    JsonArray upgradeList = JsonUtils.getJsonArray(json, "upgrades");
    Map<Ingredient, Double> upgrades = new LinkedHashMap<>();
    int n = 0;
    for (JsonElement element : upgradeList) {
        if (element.isJsonObject()) {
            JsonObject upgrade = element.getAsJsonObject();
            double amount = JsonUtils.getFloat(upgrade, "amount");
            Ingredient ingredient = CraftingHelper.getIngredient(upgrade.get("ingredient"), context);
            upgrades.put(ingredient, amount);
        } else {
            throw new JsonSyntaxException("Expected " + n + " to be a JsonObject, was " + JsonUtils.toString(json));
        }
        n++;
    }

    return new RandoresForgeUpgradeRecipe(clamp, combining, upgrades);
}
项目:GCSApp    文件:DynamicPresenter.java   
public void getData() {
    LoginData loginData = (LoginData) aCache.getAsObject(ACacheKey.CURRENT_ACCOUNT);
    addSubscription(apiStores.GetCsgData(loginData.getToken(), 1, 2), new ApiCallback<BaseModel<JsonArray>>(delegate.getActivity()) {
        @Override
        public void onSuccess(BaseModel<JsonArray> model) {
            F.e(model.getData().toString());
            GsonBuilder gsonBuilder = new GsonBuilder();
            Gson gson = gsonBuilder.create();
            ArrayList<CSGDynamic> datas = gson.fromJson(model.getData(), new TypeToken<ArrayList<CSGDynamic>>() {
            }.getType());
            delegate.setData(datas);

        }

        @Override
        public void onFailure(String msg) {
            ToastUtil.showToast(msg, delegate.getActivity());
        }

        @Override
        public void onFinish() {
        }
    });
}
项目:DecompiledMinecraft    文件:ServerStatusResponse.java   
public JsonElement serialize(ServerStatusResponse.PlayerCountData p_serialize_1_, Type p_serialize_2_, JsonSerializationContext p_serialize_3_)
{
    JsonObject jsonobject = new JsonObject();
    jsonobject.addProperty("max", (Number)Integer.valueOf(p_serialize_1_.getMaxPlayers()));
    jsonobject.addProperty("online", (Number)Integer.valueOf(p_serialize_1_.getOnlinePlayerCount()));

    if (p_serialize_1_.getPlayers() != null && p_serialize_1_.getPlayers().length > 0)
    {
        JsonArray jsonarray = new JsonArray();

        for (int i = 0; i < p_serialize_1_.getPlayers().length; ++i)
        {
            JsonObject jsonobject1 = new JsonObject();
            UUID uuid = p_serialize_1_.getPlayers()[i].getId();
            jsonobject1.addProperty("id", uuid == null ? "" : uuid.toString());
            jsonobject1.addProperty("name", p_serialize_1_.getPlayers()[i].getName());
            jsonarray.add(jsonobject1);
        }

        jsonobject.add("sample", jsonarray);
    }

    return jsonobject;
}
项目:DHIS2-fhir-lab-app    文件:FhirMediatorUtilities.java   
public static List<DataElement> getDataElementMapping (String filePath) throws Exception
{
    List<DataElement> listDataElement=new ArrayList<>();
    Gson gson=new Gson();
    try {
        JsonArray json=(JsonArray)gson.fromJson(new FileReader(filePath), JsonElement.class);
        for(int iterator=0;iterator<json.size();iterator++)
        {
            JsonElement oElement=json.get(iterator);
            DataElement oDataElement=gson.fromJson(oElement,DataElement.class);
            listDataElement.add(oDataElement);

        }
        //System.out.print(0);
    }
    catch (Exception exc)
    {
        throw new Exception(exc.toString());
    }
    return listDataElement;
}
项目:get-started-java    文件:VCAPHelper.java   
private static Entry<String, JsonElement> matchService(Set<Entry<String, JsonElement>> entries, String serviceName) {
    for (Entry<String, JsonElement> eachEntry : entries) {
                       // CF service with 'cloudant' in the name
        if (eachEntry.getKey().toLowerCase().contains(serviceName)) {
            return eachEntry;
        }
        // user-provided service with 'cloudant' in the name
        if (eachEntry.getKey().equals("user-provided")) {
            JsonArray upss = eachEntry.getValue().getAsJsonArray();
            for (JsonElement ups : upss) {
                String name = ups.getAsJsonObject().get("name").getAsString();
                if (name.toLowerCase().contains(serviceName)) {
                    return eachEntry;
                }
            }
        }
    }
    return null;
}
项目:sepatools    文件:BindingsResults.java   
public void remove(Bindings solution) {
    if (solution == null) return;
    JsonArray bindings = getBindingsArray();
    if (bindings == null) return;

    bindings.remove(solution.toJson());
}
项目:Hub    文件:BumperManager.java   
@Override
public void loadConfiguration(JsonArray rootJson)
{
    for (int i = 0; i < rootJson.size(); i++)
    {
        JsonElement jsonBumber = rootJson.get(i);

        Bumper bumper = null;

        try
        {
            bumper = new Bumper(this.hub, jsonBumber.getAsString());
        }
        catch (Exception ignored) {}

        if (bumper != null)
        {
            this.interactions.add(bumper);
            this.log(Level.INFO, "Registered bumper at '" + jsonBumber.getAsString());
        }
    }
}
项目:Backmemed    文件:VariantList.java   
public VariantList deserialize(JsonElement p_deserialize_1_, Type p_deserialize_2_, JsonDeserializationContext p_deserialize_3_) throws JsonParseException
{
    List<Variant> list = Lists.<Variant>newArrayList();

    if (p_deserialize_1_.isJsonArray())
    {
        JsonArray jsonarray = p_deserialize_1_.getAsJsonArray();

        if (jsonarray.size() == 0)
        {
            throw new JsonParseException("Empty variant array");
        }

        for (JsonElement jsonelement : jsonarray)
        {
            list.add((Variant)p_deserialize_3_.deserialize(jsonelement, Variant.class));
        }
    }
    else
    {
        list.add((Variant)p_deserialize_3_.deserialize(p_deserialize_1_, Variant.class));
    }

    return new VariantList(list);
}
项目:Backmemed    文件:EnchantRandomly.java   
public void serialize(JsonObject object, EnchantRandomly functionClazz, JsonSerializationContext serializationContext)
{
    if (!functionClazz.enchantments.isEmpty())
    {
        JsonArray jsonarray = new JsonArray();

        for (Enchantment enchantment : functionClazz.enchantments)
        {
            ResourceLocation resourcelocation = (ResourceLocation)Enchantment.REGISTRY.getNameForObject(enchantment);

            if (resourcelocation == null)
            {
                throw new IllegalArgumentException("Don\'t know how to serialize enchantment " + enchantment);
            }

            jsonarray.add(new JsonPrimitive(resourcelocation.toString()));
        }

        object.add("enchantments", jsonarray);
    }
}
项目:arquillian-reporter    文件:ReportJsonDeserializer.java   
private Report setDefaultValues(Report report, JsonObject jsonReport) {
    JsonElement name = jsonReport.get("name");
    JsonArray entries = jsonReport.get("entries").getAsJsonArray();
    JsonArray subReports = jsonReport.get("subReports").getAsJsonArray();

    report.setName(prepareGsonParser().fromJson(name, StringKey.class));


    entries.forEach(subEntry -> {
        Entry entry = prepareGsonParser().fromJson(subEntry, Entry.class);
        report.getEntries().add(entry);
    });

    subReports.forEach(subReport -> {
        Report subReportEntry = prepareGsonParser().fromJson(subReport, Report.class);
        report.getSubReports().add(subReportEntry);
    });

    return report;
}
项目:InControl    文件:PotentialSpawnRule.java   
public static PotentialSpawnRule parse(JsonElement element) {
    if (element == null) {
        return null;
    } else {
        JsonObject jsonObject = element.getAsJsonObject();
        if ((!jsonObject.has("mobs")) && (!jsonObject.has("remove"))) {
            return null;
        }

        AttributeMap map = FACTORY.parse(element);

        if (jsonObject.has("mobs")) {
            JsonArray mobs = jsonObject.get("mobs").getAsJsonArray();
            for (JsonElement mob : mobs) {
                AttributeMap mobMap = MOB_FACTORY.parse(mob);
                map.addList(ACTION_MOBS, mobMap);
            }
        }
        return new PotentialSpawnRule(map);
    }
}
项目:sonar-issueresolver-plugin    文件:PluginIT.java   
private void resolveIssues(String projectKey) {
    LOGGER.info("Listing issues for {}", projectKey);
    final SearchIssuesQuery issuesQuery = new SearchIssuesQuery(projectKey);
    final String issuesResult = orchestrator.getServer().getAdminWsClient().getConnector().execute(issuesQuery);
    final JsonObject json = new JsonParser().parse(issuesResult).getAsJsonObject();
    final JsonArray issues = json.get("issues").getAsJsonArray();
    LOGGER.info("Project {} has {} issues", projectKey, issues.size());
    for (final JsonElement issueElement : issues) {
        final JsonObject issue = issueElement.getAsJsonObject();
        if ("squid:S1220".equals(issue.get("rule").getAsString())) {
            resolveIssue(issue.get("key").getAsString(), "wontfix");
        }
        if ("squid:S106".equals(issue.get("rule").getAsString())) {
            resolveIssue(issue.get("key").getAsString(), "falsepositive");
        }
    }
}
项目:vavr-gson    文件:OptionConverter.java   
@Override
Option<?> fromJsonArray(JsonArray arr, Type type, Type[] subTypes, JsonDeserializationContext ctx) throws JsonParseException {
    if (arr.size() < 1 || arr.size() > 2) {
        throw new JsonParseException("bad json format");
    }
    String status = arr.get(0).getAsString();
    if ("defined".equals(status)) {
        if (arr.size() == 2) {
            Object el = subTypes.length > 0 ? ctx.deserialize(arr.get(1), subTypes[0]) : arr.get(1);
            return Option.some(el);
        } else {
            throw new JsonParseException("expected array size: 2");
        }
    } else {
        return Option.none();
    }
}
项目:jpl-framework    文件:LoadLearningAlgorithmsCommandTest.java   
/**
 * Tests if the {@link LoadLearningAlgorithmsCommand} is not executed due to incorrectly defined
 * parameters.
 * 
 * @throws IOException if reading the json file did not work
 * @throws IllegalAccessException if reflection did not work
 * @throws NoSuchFieldException if reflection did not work
 * @throws JsonParsingFailedException if json can't be parsed
 */
@Test
public void testAddingLearningAlgorithmsWithWrongParametersIsForbidden()
      throws IOException,
         NoSuchFieldException,
         IllegalAccessException,
         JsonParsingFailedException {

   String jsonString = IOUtils.readStringFromFile(getTestRessourcePathFor(INCORRECT_DEFINED_PARAMETERS_JSON_FILE));
   JsonArray createJsonArrayFromString = JsonUtils.createJsonArrayFromString(jsonString);
   systemConfiguration.setJsonAlgorithmConfiguration(createJsonArrayFromString);

   String[] command = { ECommand.LOAD_LEARNING_ALGORITHMS.getCommandIdentifier() };
   String consoleOutput = TestUtils.simulateCommandLineInputAndReturnConsoleOutput(command);

   assertNoLearningAlgorithmsSetInSystemConfiguration();
   assertCorrectFailedCommandResultAndConsoleOutputForAddingLearningAlgorithmsWithWrongParameters(consoleOutput);

}
项目:DRM-Desktop    文件:Message.java   
public JsonObject toJson(){
    JsonObject obj = new JsonObject();
    JsonObject message = new JsonObject();
    message.addProperty("action", action);

    JsonArray pr = new JsonArray();
    for (String key : params.keySet()) {
        pr.add(params.get(key).toJson());
    }
    message.add("params", pr);

    obj.add("message", message);

    if(this.destination != null) {
        obj.addProperty("destination", this.destination);
    }

    obj.addProperty("id", this.id.toString());

    return obj;
}
项目:Cypher    文件:ApiMock.java   
@Override
public JsonObject getPublicRooms(String server) throws RestfulHTTPException, IOException {
    JsonObject data = new JsonObject();
    JsonArray chunk = new JsonArray();

    JsonObject roomData = new JsonObject();
    roomData.addProperty("room_id", "ID1");
    chunk.add(roomData);

    JsonObject roomData2 = new JsonObject();
    roomData2.addProperty("room_id", "ID2");
    chunk.add(roomData2);

    data.add("chunk", chunk);
    return data;
}
项目:restheart-java-client    文件:RestHeartBasicClientApiTest.java   
@Test
public void testGetDocQuery() throws MalformedURLException {
    createCollection();
    insertDocInDB();
    insertDocInDB();

    String query = "filter={'name':'John'}";

    RestHeartClientResponse response = api.getDocumentsQuery(dbName, collName, query);
    Assert.assertNotNull("Response is null", response);

    JsonObject responseObject = response.getResponseObject();
    Assert.assertNotNull("Json object response is null", responseObject);

    JsonArray jsonArray = responseObject
        .get("_embedded")
        .getAsJsonArray();

    Assert.assertEquals("Return Collection Name not 2 as expected", 2, jsonArray.size());

    LOGGER.info(GsonUtils.toJson(response.getResponseObject()));
}
项目:modName    文件:Settings.java   
static <T extends IJsonMappable> void readJsonableMap(JsonObject o, LinkedHashMap<String, T> list, String tagname, Class<T> clazz) {
    list.clear();
    if (o.has(tagname)) {
        JsonArray g = JsonUtil.getAsArray(o, tagname); //o.getAsJsonArray(tagname);
        for (JsonElement element : g) {
            T def = IJsonable.create(clazz);
            JsonObject eo;
            /*try {
                eo = element.getAsJsonObject();
            } catch (Exception e) {
                return;
            }*/
            eo = JsonUtil.asObject(element);
            def.fromJson(eo);
            list.put(def.getMapKey(), def);
        }
    }

}
项目:TruenoNPC    文件:TruenoNPC_v1_9_r1.java   
private void cacheSkin(SkinData skindata){
    JsonObject jsonFile = getChacheFile(plugin);
    JsonArray newskindata = new JsonArray();
    if(jsonFile!=null){
        JsonArray oldskindata = jsonFile.getAsJsonArray("skindata");
        Iterator it = oldskindata.iterator();
        while(it.hasNext()){
            JsonElement element = (JsonElement) it.next();
            if(element.getAsJsonObject().get("id").getAsInt()==this.npcid){
                // element.getAsJsonObject().remove("value");
                //element.getAsJsonObject().remove("signature");
                //element.getAsJsonObject().addProperty("value", skindata.getValue());
                //element.getAsJsonObject().addProperty("signature", skindata.getSignature());
            }else {
                newskindata.add(element);
            }
        }
    }
    JsonObject skin = new JsonObject();
    skin.addProperty("id", this.npcid);
    skin.addProperty("value", skindata.getValue());
    skin.addProperty("signature", skindata.getSignature());
    newskindata.add(skin);

    JsonObject obj = new JsonObject();
    obj.add("skindata", newskindata);
    try {
        plugin.getDataFolder().mkdir();
        File file = new File(plugin.getDataFolder().getPath()+"/truenonpcdata.json");
        file.createNewFile();
        FileWriter writer = new FileWriter(file);
        writer.write(obj.toString());
        writer.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:ja-micro    文件:ProtobufUtilTest.java   
@Test
public void jsonToProtobuf_JsonArrayWithTwoElements_ParseFirstOne() throws Exception {
    // given
    JsonArray jsonArray = new JsonArray();
    jsonArray.add(new JsonParser().parse("{\"id\":\"1\"}"));
    jsonArray.add(new JsonParser().parse("{\"id\":\"2\"}"));

    // when
    FrameworkTest.SerializationTest message = ProtobufUtil.jsonToProtobuf(jsonArray, FrameworkTest.SerializationTest.class);

    // then
    assertThat(message.getId()).isEqualTo("1");
}
项目:TruenoNPC    文件:TruenoNPC_v1_12_r1.java   
private SkinData getCachedSkin(){
    JsonObject jsonFile = getChacheFile(plugin);
    JsonArray oldskindata = jsonFile.getAsJsonArray("skindata");
    Iterator it = oldskindata.iterator();
    SkinData skin = null;
    while(it.hasNext()){
        JsonElement element = (JsonElement) it.next();
        if(element.getAsJsonObject().get("id").getAsInt()==this.npcid){
            String value = element.getAsJsonObject().get("value").getAsString();
            String signature = element.getAsJsonObject().get("signature").getAsString();
            skin = new SkinData(value, signature);
        }
    }
    return skin;
}
项目:Proyecto-DASI    文件:ObservationFromChatImplementation.java   
@Override
public void writeObservationsToJSON(JsonObject json, MissionInit missionInit)
{
    if (!this.chatMessagesReceived.isEmpty())
    {
        JsonArray arr = new JsonArray();
        for (String obs : this.chatMessagesReceived)
        {
            arr.add(new JsonPrimitive(obs));
        }
        json.add("Chat", arr);
        this.chatMessagesReceived.clear();
    }
}
项目:ja-micro    文件:JsonRpcRequestTest.java   
@Test
public void gettersAndSetters() {
    JsonArray array = new JsonArray();
    JsonRpcRequest req = new JsonRpcRequest(null, "mefod", array);
    assertThat(req.getMethod()).isEqualTo("mefod");
    assertThat(req.getParams()).isEqualTo(array);
}
项目:Habitizer    文件:ElasticsearchController.java   
@Override
protected JsonArray doInBackground(String... search_parameters) {
    verifySettings();
    JsonArray userData = null;

    // TODO Build the query
    String query = "{\n" +
            "\"size\" : 1000,"+
            "     \"query\" : {\n" +
            "        \"term\": { \"" + search_parameters[1] + "\": \"" + search_parameters[2] + "\"}\n" +
            "     }\n" +
            "}";

    Search search = new Search.Builder(query)
            .addIndex(INDEX)
            .addType(search_parameters[0])
            .build();

    try {
        // TODO get the results of the query
        SearchResult result = client.execute(search);
        JsonObject hits = result.getJsonObject().getAsJsonObject("hits");
       /* Gson g = new Gson();
        String s = g.toJson(hits);
        Log.d("ESC.json", s);*/
        if (result.isSucceeded()) {
            userData = hits.getAsJsonArray("hits");
        } else {
            Log.i("Error", "The search query failed to find any users that matched");
        }
    } catch (Exception e) {
        Log.i("Error", "Something went wrong when we tried to communicate with the elasticsearch server!");
    }

    return userData;
}
项目:digital-display-garden-iteration-4-revolverenguardia-1    文件:GardenCharts.java   
/**
 * Creates a two dimensional Json array from an Object[][] in.
 *
 * Valid Objects to put in the Object[][] are Strings, Numbers (bool, integer, double, etc.), and JsonElements
 *
 * @param in
 * @return
 */
public String makeJSON(Object[][] in) {

    JsonArray outerArray = new JsonArray();
    for(int i = 0; i < in.length; i++) {
        JsonArray innerArray = new JsonArray();
        for(int j = 0; j < in[i].length; j++) {
            Object a = in[i][j];
            Class objectClass = a.getClass();
            if(objectClass == String.class)
            {
                innerArray.add(in[i][j].toString());
            }
            else if(Number.class.isAssignableFrom(objectClass))
            {
                innerArray.add((Number)in[i][j]);
            }
            else if(objectClass == JsonElement.class)
            {
                innerArray.add((JsonElement)in[i][j]);
            }
            else
            {
                throw new RuntimeException("WHAT ARE YOU");
            }
        }

        outerArray.add(innerArray);
    }
    return outerArray.toString();
}
项目:mxhsd    文件:RoomDirectoryController.java   
@RequestMapping(method = GET, path = "/directory")
public String queryRoomAlias(HttpServletRequest req, @RequestParam("room_alias") String roomAlias) {
    log(req);

    IRoomAliasLookup lookup = hs.getServerSession("").getDirectory().lookup(roomAlias)
            .orElseThrow(() -> new NotFoundException("No room with alias " + roomAlias + " exists"));

    JsonArray servers = new JsonArray();
    lookup.getServers().forEach(servers::add);
    JsonObject body = new JsonObject();
    body.addProperty("room_id", lookup.getId());
    body.add("servers", servers);

    return toJson(body);
}
项目:TruenoNPC    文件:TruenoNPC_v1_9_r1.java   
private SkinData getCachedSkin(){
    JsonObject jsonFile = getChacheFile(plugin);
    JsonArray oldskindata = jsonFile.getAsJsonArray("skindata");
    Iterator it = oldskindata.iterator();
    SkinData skin = null;
    while(it.hasNext()){
        JsonElement element = (JsonElement) it.next();
        if(element.getAsJsonObject().get("id").getAsInt()==this.npcid){
            String value = element.getAsJsonObject().get("value").getAsString();
            String signature = element.getAsJsonObject().get("signature").getAsString();
            skin = new SkinData(value, signature);
        }
    }
    return skin;
}
项目:pnc-repressurized    文件:AmadronOfferConfig.java   
@Override
protected final void readFromJson(JsonObject json) {
    readFromJsonCustom(json);
    JsonArray array = (JsonArray) json.get("offers");
    Collection<AmadronOffer> offers = getOffers();
    offers.clear();
    for (JsonElement element : array) {
        AmadronOffer offer = ((JsonObject) element).has("inStock") ? AmadronOfferCustom.fromJson((JsonObject) element) : AmadronOffer.fromJson((JsonObject) element);
        if (offer != null) {
            offers.add(offer);
        }
    }
}
项目:Phoenix-for-VK    文件:LongpollUpdateAdapter.java   
private AddMessageUpdate deserializeAddMessageUpdate(JsonArray array){
    AddMessageUpdate update = new AddMessageUpdate();

    update.message_id = optInt(array, 1);
    update.flags = optInt(array, 2);
    update.peer_id = optInt(array, 3);
    update.timestamp = optLong(array, 4);
    update.subject = optString(array, 5);
    update.text = VKStringUtils.unescape(optString(array, 6));

    JsonObject attachments = (JsonObject) opt(array, 7);

    if(nonNull(attachments)){
        update.from = optInt(attachments, "from");
        update.sourceText = optString(attachments, "source_text");
        update.sourceAct = optString(attachments, "source_act");
        update.sourceMid = optInt(attachments, "source_mid");

        String fwd = optString(attachments, "fwd");
        if(nonNull(fwd)){
            update.fwds = parseLineWithSeparators(fwd, ",");
        }
    }

    update.random_id = optString(array, 8);

    if(!hasFlag(update.flags, VKApiMessage.FLAG_GROUP_CHAT) && !hasFlag(update.flags, VKApiMessage.FLAG_OUTBOX)){
        update.from = update.peer_id;
    }

    return update;
}
项目:Vigilate    文件:Metrics.java   
/**
 * Collects the data and sends it afterwards.
 */
private void submitData() {
    final JsonObject data = getServerData();

    JsonArray pluginData = new JsonArray();
    // Search for all other bStats Metrics classes to get their plugin data
    for (Object metrics : knownMetricsInstances) {
        try {
            Object plugin = metrics.getClass().getMethod("getPluginData").invoke(metrics);
            if (plugin instanceof JsonObject) {
                pluginData.add((JsonObject) plugin);
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { }
    }

    data.add("plugins", pluginData);

    // Create a new thread for the connection to the bStats server
    new Thread(() ->  {
        try {
            // Send the data
            sendData(data);
        } catch (Exception e) {
            // Something went wrong! :(
            if (logFailedRequests) {
                logger.warn("Could not submit plugin stats!", e);
            }
        }
    }).start();
}
项目:Redunda-lib-java    文件:DataService.java   
/**
 * Returns the list of files on the server as `JsonArray`
 * 
 * @throws Throwable If the download/parsing fails
 * 
 * @return An array of objects with information about the stored files
 * */
public JsonArray getRemoteFileList() throws Throwable {
    String url = "https://redunda.sobotics.org/bots/data.json?key="+this.apiKey;
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    //add request header
    con.setRequestMethod("GET");
    con.setRequestProperty("User-Agent", UserAgent.getUserAgent());

    con.getResponseCode();

    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    String responseString = response.toString();
    //System.out.println(responseString);

    //http://stackoverflow.com/a/15116323/4687348
    JsonParser jsonParser = new JsonParser();
    JsonArray array = (JsonArray)jsonParser.parse(responseString);
    return array;
    /*
    List<String> filenames = new ArrayList<String>();

    for (JsonElement element : array) {
        JsonObject elementObject = element.getAsJsonObject();
        String key = elementObject.get("key").getAsString();
        if (key != null) {
            String decodedKey = this.decodeFilename(key);
            filenames.add(decodedKey);
        }
    }

    return filenames;*/
}
项目:dsp4e    文件:DebugMessageTypeAdapterFactory.java   
protected Object parseParams(Object params, String method) {
    if (isNull(params)) {
        return null;
    }
    if (!(params instanceof JsonElement)) {
        return params;
    }
    JsonElement rawParams = (JsonElement) params;
    Type[] parameterTypes = getParameterTypes(method);
    if (parameterTypes.length == 1) {
        return fromJson(rawParams, parameterTypes[0]);
    }
    if (parameterTypes.length > 1 && rawParams instanceof JsonArray) {
        JsonArray array = (JsonArray) rawParams;
        List<Object> parameters = new ArrayList<Object>(Math.max(array.size(), parameterTypes.length));
        int index = 0;
        Iterator<JsonElement> iterator = array.iterator();
        while (iterator.hasNext()) {
            Type parameterType = index < parameterTypes.length ? parameterTypes[index] : null;
            Object parameter = fromJson(iterator.next(), parameterType);
            parameters.add(parameter);
            index++;
        }
        while (index < parameterTypes.length) {
            parameters.add(null);
            index++;
        }
        return parameters;
    }
    return rawParams;
}