Java Examples for com.google.gson.JsonArray
The following java examples will help you to understand the usage of com.google.gson.JsonArray. These source code samples are taken from different open source projects.
Example 1
| Project: puree-android-master File: PureeBufferedOutput.java View source code |
public void flushSync() {
if (!storage.lock()) {
return;
}
final Records records = getRecordsFromStorage();
if (records.isEmpty()) {
storage.unlock();
return;
}
final JsonArray jsonLogs = records.getJsonLogs();
emit(jsonLogs, new AsyncResult() {
@Override
public void success() {
flushTask.reset();
storage.delete(records);
storage.unlock();
}
@Override
public void fail() {
flushTask.retryLater();
storage.unlock();
}
});
}Example 2
| Project: android_xcore-master File: GsonPrimitiveJoinerConverter.java View source code |
@Override
public void convert(Params params) {
StringBuilder tagsBuilder = new StringBuilder();
JsonArray jsonArray = params.getJsonArray();
for (int i = 0; i < jsonArray.size(); i++) {
JsonElement item = jsonArray.get(i);
tagsBuilder.append(item.getAsString());
if (i != jsonArray.size() - 1) {
tagsBuilder.append(getSplitter());
}
}
String result = tagsBuilder.toString();
Log.xd(this, "tagsJsonConverter " + result);
if (!StringUtil.isEmpty(result)) {
params.getContentValues().put(getEntityKey(), result);
}
}Example 3
| Project: bennu-master File: TaskResource.java View source code |
@GET
@Produces(MediaType.APPLICATION_JSON)
public JsonObject getTasks() {
accessControl(Group.managers());
final JsonObject objContainer = new JsonObject();
final JsonArray tasks = new JsonArray();
for (Entry<String, Task> taskEntry : SchedulerSystem.getTasks().entrySet()) {
final JsonObject taskJson = new JsonObject();
taskJson.addProperty("type", taskEntry.getKey());
taskJson.addProperty("name", taskEntry.getValue().englishTitle());
tasks.add(taskJson);
}
objContainer.add("tasks", tasks);
return objContainer;
}Example 4
| Project: DeviveWallSuite-master File: MemoryAssign.java View source code |
@Override
public JsonObject toJson() {
final JsonArray jsonArray = new JsonArray();
for (final Integer picId : pic_ids) {
final JsonElement jsonElement = new JsonPrimitive(picId);
jsonArray.add(jsonElement);
}
final JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("id", id);
jsonObject.add("pic_ids", jsonArray);
return jsonObject;
}Example 5
| Project: MinecraftNetLib-master File: TranslationMessage.java View source code |
@Override
public JsonElement toJson() {
JsonElement jsonElement = super.toJson();
if (jsonElement.isJsonObject()) {
JsonObject jsonObject = jsonElement.getAsJsonObject();
jsonObject.addProperty("translate", this.translateKey);
JsonArray array = new JsonArray();
for (Message message : this.translationParts) {
array.add(message.toJson());
}
jsonObject.add("with", array);
return jsonObject;
}
return jsonElement;
}Example 6
| Project: sky-walking-master File: JsonDataMerge.java View source code |
public void merge(String expectJsonFile, JsonArray actualData) throws FileNotFoundException { Gson gson = new Gson(); String jsonStrData = JsonFileReader.INSTANCE.read(path + expectJsonFile); JsonArray expectJsonArray = gson.fromJson(jsonStrData, JsonArray.class); for (int i = 0; i < expectJsonArray.size(); i++) { JsonObject expectJson = expectJsonArray.get(i).getAsJsonObject(); mergeData(expectJson, actualData.get(i).getAsJsonObject()); } }
Example 7
| Project: slack4gerrit-master File: CherryPicksHelper.java View source code |
static String getCherryPickLegacyId(String cherryPickRequestJSONResponse) {
LOGGER.debug("parsing Cherry pick request : " + cherryPickRequestJSONResponse);
cherryPickRequestJSONResponse = cherryPickRequestJSONResponse.substring(4);
JsonParser parser = new JsonParser();
long lowestLegacyId = Long.MAX_VALUE;
JsonArray obj = parser.parse(cherryPickRequestJSONResponse).getAsJsonArray();
for (JsonElement jsonElement : obj) {
JsonObject jsonChange = jsonElement.getAsJsonObject();
long cherryPickLegacyId = GsonHelper.getLongOrNull(jsonChange.get("_number"));
if (cherryPickLegacyId < lowestLegacyId) {
lowestLegacyId = cherryPickLegacyId;
}
}
return Long.toString(lowestLegacyId);
}Example 8
| Project: sync-service-master File: CommonFunctions.java View source code |
private static JsonArray generateObjectsLevel(int numObjects, UUID deviceId, ParentRoot parentRoot) { JsonArray arrayObjects = new JsonArray(); Random random = new Random(); RandomString strRandom = new RandomString(10); for (int i = 0; i < numObjects; i++) { JsonObject file = new JsonObject(); file.addProperty("file_id", random.nextLong()); file.addProperty("version", new Long(1)); if (parentRoot != null) { file.addProperty("parent_file_version", parentRoot.fileVersion); file.addProperty("parent_file_id", parentRoot.fileId); } else { file.addProperty("parent_file_version", ""); file.addProperty("parent_file_id", ""); } Date date = new Date(); file.addProperty("updated", date.getTime()); file.addProperty("status", "NEW"); file.addProperty("lastModified", date.getTime()); file.addProperty("checksum", random.nextLong()); file.addProperty("clientName", deviceId.toString()); file.addProperty("fileSize", random.nextLong()); file.addProperty("folder", 0); file.addProperty("name", strRandom.nextString()); file.addProperty("path", strRandom.nextString()); file.addProperty("mimetype", "Text"); file.add("chunks", generateChunks(10)); arrayObjects.add(file); } return arrayObjects; }
Example 9
| Project: the-blue-alliance-android-master File: EventRenderer.java View source code |
@WorkerThread
public List<WebcastListElement> renderWebcasts(Event event) {
List<WebcastListElement> webcasts = new ArrayList<>();
JsonArray webcastJson = JSONHelper.getasJsonArray(event.getWebcasts());
JsonElement webcast;
for (int i = 1; i <= webcastJson.size(); i++) {
webcast = webcastJson.get(i - 1);
webcasts.add(new WebcastListElement(event.getKey(), event.getShortName(), webcast.getAsJsonObject(), i));
}
return webcasts;
}Example 10
| Project: YourAppIdea-master File: LocationDeserializer.java View source code |
@Override
public Location deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
JsonObject jsonObject = jsonElement.getAsJsonObject();
Location location = new Location("mongodb");
JsonArray coord = jsonObject.getAsJsonArray("coordinates");
location.setLongitude(coord.get(0).getAsDouble());
location.setLatitude(coord.get(1).getAsDouble());
return location;
}Example 11
| Project: Avengers-master File: MarvelResultsComicsDeserialiser.java View source code |
@Override
public List<Comic> deserialize(JsonElement je, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Type listType = new TypeToken<List<Comic>>() {
}.getType();
JsonElement data = je.getAsJsonObject().get("data");
JsonElement results = je.getAsJsonObject().get("results");
JsonArray resultsArray = results.getAsJsonArray();
JsonElement comicsObject = resultsArray.get(0);
JsonElement items = comicsObject.getAsJsonObject().get("items");
return new Gson().fromJson(items, listType);
}Example 12
| Project: breakout-master File: Gson2SnakeYaml.java View source code |
public static Object toSnakeYaml(JsonElement elem) {
if (elem instanceof JsonPrimitive) {
return ((JsonPrimitive) elem).getAsString();
} else if (elem instanceof JsonObject) {
return toSnakeYamlMap((JsonObject) elem);
} else if (elem instanceof JsonArray) {
return toSnakeYamlList((JsonArray) elem);
} else {
return null;
}
}Example 13
| Project: ciel-java-master File: FirstClassJavaTaskInformation.java View source code |
public JsonObject toJson() {
JsonObject ret = new JsonObject();
ret.add("executor_name", new JsonPrimitive("java2"));
if (this.numOutputs > 0) {
ret.add("n_outputs", new JsonPrimitive(this.numOutputs));
}
if (this.className != null) {
ret.add("class_name", new JsonPrimitive(this.className));
} else if (this.objectRef != null) {
ret.add("object_ref", this.objectRef.toJson());
} else {
assert false;
}
JsonArray jsonJarLib = new JsonArray();
for (Reference jarRef : this.jarLib) {
jsonJarLib.add(jarRef.toJson());
}
ret.add("jar_lib", jsonJarLib);
JsonArray jsonDependencies = new JsonArray();
for (Reference depRef : this.dependencies) {
jsonDependencies.add(depRef.toJson());
}
ret.add("extra_dependencies", jsonDependencies);
if (this.args != null) {
JsonArray jsonArgs = new JsonArray();
for (String arg : args) {
jsonArgs.add(new JsonPrimitive(arg));
}
ret.add("args", jsonArgs);
}
return ret;
}Example 14
| Project: collaboro-master File: LanguagesAvailableServlet.java View source code |
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
addResponseOptions(response);
response.setContentType("application/json");
PrintWriter out = response.getWriter();
JsonArray languages = new JsonArray();
for (String languageName : CollaboroBackendFactory.getActiveLanguages()) {
JsonElement languageElement = new JsonPrimitive(languageName);
languages.add(languageElement);
}
JsonObject jsonResponse = new JsonObject();
jsonResponse.add("languages", languages);
out.print(jsonResponse.toString());
}Example 15
| Project: CouchbaseMock-master File: PoolsHandlerTest.java View source code |
/**
* Test of getPoolsJSON method, of class PoolsHandler.
*/
public void testGetPoolsJSON() {
PoolsHandler instance = new PoolsHandler(mock);
assertNotNull(instance);
String result = StateGrabber.getAllPoolsJSON(mock);
JsonObject jObj = new Gson().fromJson(result, JsonObject.class);
JsonArray poolsArray;
assertNotNull(jObj);
assertTrue(jObj.has("isAdminCreds"));
assertTrue(jObj.get("isAdminCreds").getAsBoolean());
assertTrue(jObj.has("pools"));
poolsArray = jObj.getAsJsonArray("pools");
assertNotNull(jObj);
JsonObject firstPool = poolsArray.get(0).getAsJsonObject();
assertNotNull(firstPool);
assertEquals(firstPool.get("name").getAsString(), "default");
assertEquals(firstPool.get("streamingUri").getAsString(), "/poolsStreaming/default");
assertEquals(firstPool.get("uri").getAsString(), "/pools/default");
}Example 16
| Project: gson-fire-master File: JsonUtils.java View source code |
/**
* Copies all the property values from the supplied {@link JsonElement}. This method is similar to
* {@link JsonElement#deepCopy()}. We are not using {@link JsonElement#deepCopy()} because it is not public
* @param from
* @return
*/
public static JsonElement deepCopy(JsonElement from) {
if (from.isJsonObject()) {
JsonObject result = new JsonObject();
for (Map.Entry<String, JsonElement> entry : from.getAsJsonObject().entrySet()) {
result.add(entry.getKey(), deepCopy(entry.getValue()));
}
return result;
} else if (from.isJsonArray()) {
JsonArray result = new JsonArray();
for (JsonElement element : from.getAsJsonArray()) {
result.add(element);
}
return result;
} else if (from.isJsonPrimitive()) {
return from;
} else if (from.isJsonNull()) {
return from;
} else {
return JsonNull.INSTANCE;
}
}Example 17
| Project: hibernate-search-master File: FileAsLineArrayParameterValueTransformer.java View source code |
@Override
public JsonElement transform(String parameterValue) {
JsonArray array = new JsonArray();
for (String filePath : FILE_PATH_SEPARATOR_PATTERN.split(parameterValue)) {
try (final InputStream stream = resourceLoader.openResource(filePath)) {
List<String> lines = getLines(stream);
for (String line : lines) {
array.add(new JsonPrimitive(line));
}
} catch (IOExceptionSearchException | e) {
throw new SearchException("Could not parse file: " + parameterValue, e);
}
}
return array;
}Example 18
| Project: intellij-plugins-master File: Stack.java View source code |
public ElementList<Frame> getAsyncCausalFrames() {
if (json.get("asyncCausalFrames") == null)
return null;
return new ElementList<Frame>(json.get("asyncCausalFrames").getAsJsonArray()) {
@Override
protected Frame basicGet(JsonArray array, int index) {
return new Frame(array.get(index).getAsJsonObject());
}
};
}Example 19
| Project: javers-master File: CommitPropertiesConverter.java View source code |
static JsonElement toJson(Map<String, String> properties) {
JsonArray propertiesArray = new JsonArray();
if (properties != null) {
for (Map.Entry<String, String> metadata : properties.entrySet()) {
JsonObject propertyObject = new JsonObject();
propertyObject.add(PROPERTY_KEY_FIELD, new JsonPrimitive(metadata.getKey()));
propertyObject.add(PROPERTY_VALUE_FIELD, new JsonPrimitive(metadata.getValue()));
propertiesArray.add(propertyObject);
}
}
return propertiesArray;
}Example 20
| Project: jena-sparql-api-master File: JsonVisitorRewriteSparqlService.java View source code |
@Override
public JsonElement visit(JsonObject json) {
JsonElement result;
if (json.has("$sparqlService")) {
JsonArray arr = json.get("$sparqlService").getAsJsonArray();
JsonObject o = new JsonObject();
o.addProperty("type", "org.aksw.jena_sparql_api.batch.step.FactoryBeanSparqlService");
o.add("service", JsonUtils.safeGet(arr, 0));
o.add("dataset", JsonUtils.safeGet(arr, 1));
o.add("auth", JsonUtils.safeGet(arr, 2));
result = o;
} else {
result = json;
}
return result;
}Example 21
| Project: LIMO-master File: ScheduleLegSerializer.java View source code |
@Override
public JsonElement serialize(ScheduledLeg src, Type typeOfSrc, JsonSerializationContext context) {
Gson g = GsonHelper.getInstance();
Leg hLeg = new Leg(src);
hLeg.setNext(src.getNext());
JsonObject ele1 = (JsonObject) g.toJsonTree(hLeg);
ele1.add("expectedTime", new JsonPrimitive(src.getExpectedTime()));
ele1.add("delay", new JsonPrimitive(src.getDelay()));
ele1.add("waitingTimeLimit", new JsonPrimitive(src.getWaitingTimeLimit()));
JsonArray array = new JsonArray();
ArrayList<Long> list = (ArrayList) src.getAcceptanceTimes();
list.stream().forEach(( acceptedTime) -> {
array.add(new JsonPrimitive(acceptedTime));
});
ele1.add("acceptanceTimes", array);
ele1.add("alternative", g.toJsonTree(src.getAlternative()));
return ele1;
}Example 22
| Project: Minecraft-Resource-Calculator-2-master File: CraftingTreeView.java View source code |
public void process(ICraftingTree tree_node) {
this.json_object.add("item", new JsonPrimitive(tree_node.getResult()));
this.json_object.add("amount", new JsonPrimitive(tree_node.getAmount()));
this.json_object.add("excess", new JsonPrimitive(tree_node.isExcess()));
this.json_object.add("recipe-count", new JsonPrimitive(tree_node.getRecipeCount()));
this.json_object.add("is-used-tool", new JsonPrimitive(tree_node instanceof UsedToolCraftingTree));
JsonArray ingredients = new JsonArray();
for (ICraftingTree ingredient : tree_node.getIngredients()) {
CraftingTreeView ingredient_view = new CraftingTreeView();
ingredient_view.process(ingredient);
ingredients.add(ingredient_view.getJsonObject());
}
this.json_object.add("ingredients", ingredients);
if (tree_node.getRecipe() != null) {
RecipeView recipe_view = new RecipeView();
recipe_view.process(tree_node.getRecipe());
this.json_object.add("recipe", recipe_view.getJsonObject());
}
}Example 23
| Project: moap-master File: TestFeaterable.java View source code |
@Override
public IFeature getFeature() {
// TODO Auto-generated method stub
return new IFeature() {
@Override
public JsonObject toJson() {
// TODO Auto-generated method stub
return new JsonObject();
}
@Override
public JsonArray getProperties() {
// TODO Auto-generated method stub
return null;
}
@Override
public IGeometry getGeometry() {
// TODO Auto-generated method stub
return new IGeometry() {
@Override
public JsonObject toJson() {
// TODO Auto-generated method stub
return null;
}
@Override
public GeometryType getGeometryType() {
// TODO Auto-generated method stub
return GeometryType.POINT;
}
@Override
public double[][] getCoordinates() {
// TODO Auto-generated method stub
double[][] point = new double[1][2];
return point;
}
};
}
};
}Example 24
| Project: olca-modules-master File: UnitGroupWriter.java View source code |
private void mapUnits(UnitGroup group, JsonObject json) {
JsonArray units = new JsonArray();
for (Unit unit : group.getUnits()) {
JsonObject obj = new JsonObject();
addBasicAttributes(unit, obj);
if (Objects.equals(unit, group.getReferenceUnit()))
Out.put(obj, "referenceUnit", true);
Out.put(obj, "conversionFactor", unit.getConversionFactor());
mapSynonyms(unit, obj);
units.add(obj);
}
Out.put(json, "units", units);
}Example 25
| Project: opendata-master File: JsonNoteSink.java View source code |
@Override
public void dump(Collection<NoteEntry> notes, ICommandSender sender) throws CommandException {
JsonArray result = new JsonArray();
for (NoteEntry note : notes) {
JsonObject object = note.toJson();
result.add(object);
}
try {
IDataSource<Object> target = notesDump.createNew();
target.store(result);
sender.addChatMessage(new TextComponentTranslation("openeye.chat.dumped", target.getId()));
} catch (Throwable t) {
Log.warn(t, "Failed to store notes");
throw new CommandException("openeye.chat.store_failed");
}
}Example 26
| Project: PerWorldInventory-master File: PotionEffectSerializerTest.java View source code |
@Test
public void serializePotionEffectWithParticlesAndColor() {
// given
ArrayList<PotionEffect> effects = new ArrayList<>();
PotionEffect effect = new PotionEffect(PotionEffectType.CONFUSION, 30, 1, true, true, Color.AQUA);
effects.add(effect);
// when
JsonArray serialized = PotionEffectSerializer.serialize(effects);
// then
JsonObject json = serialized.get(0).getAsJsonObject();
assertTrue(json.get("type").getAsString().equals("CONFUSION"));
assertTrue(json.get("amp").getAsInt() == 1);
assertTrue(json.get("duration").getAsInt() == 30);
assertTrue(json.get("ambient").getAsBoolean());
assertTrue(json.get("particles").getAsBoolean());
assertTrue(Color.fromRGB(json.get("color").getAsInt()) == Color.AQUA);
}Example 27
| Project: PneumaticCraft-master File: JsonToNBTConverter.java View source code |
private NBTTagCompound getTag(JsonObject object) {
NBTTagCompound nbt = new NBTTagCompound();
for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
JsonObject keyObject = entry.getValue().getAsJsonObject();
int type = keyObject.get("type").getAsInt();
JsonElement element = keyObject.get("value");
switch(type) {
case 1:
nbt.setByte(entry.getKey(), (byte) element.getAsDouble());
break;
case 2:
nbt.setShort(entry.getKey(), (short) element.getAsDouble());
case 3:
nbt.setInteger(entry.getKey(), (int) element.getAsDouble());
break;
case 4:
nbt.setLong(entry.getKey(), (long) element.getAsDouble());
break;
case 5:
nbt.setFloat(entry.getKey(), (float) element.getAsDouble());
break;
case 6:
nbt.setDouble(entry.getKey(), element.getAsDouble());
break;
// break;
case 8:
nbt.setString(entry.getKey(), element.getAsString());
break;
case 9:
JsonArray array = element.getAsJsonArray();
NBTTagList tagList = new NBTTagList();
for (JsonElement e : array) {
tagList.appendTag(getTag(e.getAsJsonObject()));
}
nbt.setTag(entry.getKey(), tagList);
break;
case 10:
nbt.setTag(entry.getKey(), getTag(element.getAsJsonObject()));
break;
case 11:
array = element.getAsJsonArray();
int[] intArray = new int[array.size()];
for (int i = 0; i < array.size(); i++) {
intArray[i] = array.get(i).getAsInt();
}
nbt.setTag(entry.getKey(), new NBTTagIntArray(intArray));
break;
default:
throw new IllegalArgumentException("NBT type no " + type + " is not supported by the Json to NBT converter!");
}
}
return nbt;
}Example 28
| Project: Robin-Client-master File: ChannelMessage.java View source code |
@Override
public List<ChannelMessage> createListFrom(JsonElement element) {
try {
JsonArray messageArray = element.getAsJsonArray();
ArrayList<ChannelMessage> messages = new ArrayList<ChannelMessage>(messageArray.size());
for (JsonElement messageElement : messageArray) {
ChannelMessage message = new ChannelMessage().createFrom(messageElement);
if (message != null) {
messages.add(message);
}
}
return messages;
} catch (Exception e) {
Debug.out(e);
}
return null;
}Example 29
| Project: round-java-master File: PassphraseBoxTest.java View source code |
@DataPoints
public static List<TestCyphertext> cipherTexts() throws URISyntaxException, FileNotFoundException, IOException {
JsonObject json = Utils.loadJsonResource("/wallet_ciphertexts.json");
JsonArray jsonCiphertexts = json.getAsJsonArray("ciphertexts");
ArrayList<TestCyphertext> ciphertexts = new ArrayList<>();
for (JsonElement e : jsonCiphertexts) {
JsonObject obj = e.getAsJsonObject();
TestCyphertext ciphertext = new TestCyphertext();
ciphertext.passphrase = obj.get("passphrase").getAsString();
ciphertext.cleartext = obj.get("cleartext").getAsString();
ciphertext.encrypted = EncryptedMessage.fromJson(obj.get("encrypted").getAsJsonObject());
ciphertexts.add(ciphertext);
}
return ciphertexts;
}Example 30
| Project: SimpleNews-master File: NewsJsonUtils.java View source code |
/**
* 将获�到的json转�为新闻列表对象
* @param res
* @param value
* @return
*/
public static List<NewsBean> readJsonNewsBeans(String res, String value) {
List<NewsBean> beans = new ArrayList<NewsBean>();
try {
JsonParser parser = new JsonParser();
JsonObject jsonObj = parser.parse(res).getAsJsonObject();
JsonElement jsonElement = jsonObj.get(value);
if (jsonElement == null) {
return null;
}
JsonArray jsonArray = jsonElement.getAsJsonArray();
for (int i = 1; i < jsonArray.size(); i++) {
JsonObject jo = jsonArray.get(i).getAsJsonObject();
if (jo.has("skipType") && "special".equals(jo.get("skipType").getAsString())) {
continue;
}
if (jo.has("TAGS") && !jo.has("TAG")) {
continue;
}
if (!jo.has("imgextra")) {
NewsBean news = JsonUtils.deserialize(jo, NewsBean.class);
beans.add(news);
}
}
} catch (Exception e) {
LogUtils.e(TAG, "readJsonNewsBeans error", e);
}
return beans;
}Example 31
| Project: tabula-java-master File: TableSerializer.java View source code |
@Override
public JsonElement serialize(Table table, Type type, JsonSerializationContext context) {
JsonObject object = new JsonObject();
if (table.getExtractionAlgorithm() == null) {
object.addProperty("extraction_method", "");
} else {
object.addProperty("extraction_method", (table.getExtractionAlgorithm()).toString());
}
object.addProperty("top", table.getTop());
object.addProperty("left", table.getLeft());
object.addProperty("width", table.getWidth());
object.addProperty("height", table.getHeight());
JsonArray jsonDataArray = new JsonArray();
for (List<RectangularTextContainer> row : table.getRows()) {
JsonArray jsonRowArray = new JsonArray();
for (RectangularTextContainer textChunk : row) {
jsonRowArray.add(context.serialize(textChunk));
}
jsonDataArray.add(jsonRowArray);
}
object.add("data", jsonDataArray);
return object;
}Example 32
| Project: TwAndroid-master File: DeserializeWorkoutHolder.java View source code |
@Override
public List<WorkoutHolderModel> deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException {
JsonElement workoutHolder = je.getAsJsonObject().get("data");
Type listType = new TypeToken<List<WorkoutHolderModel>>() {
}.getType();
List<WorkoutHolderModel> workoutHolders = new Gson().fromJson(workoutHolder, listType);
JsonArray workouts = workoutHolder.getAsJsonArray();
int index = 0;
for (JsonElement workout : workouts) {
List<WorkoutsExercisesModel> workoutExercises = new ArrayList<WorkoutsExercisesModel>();
JsonElement exercises = workout.getAsJsonObject().get("exercises");
for (JsonElement exercise : exercises.getAsJsonArray()) {
WorkoutsExercisesModel exe = new Gson().fromJson(exercise.getAsJsonObject().get("exercise"), WorkoutsExercisesModel.class);
workoutExercises.add(exe);
}
workoutHolders.get(index).setExercises(workoutExercises);
index++;
}
return workoutHolders;
}Example 33
| Project: writelatex-git-bridge-master File: SnapshotPostbackRequestInvalidProject.java View source code |
@Override
public JsonObject toJson() {
JsonObject jsonThis = super.toJson();
jsonThis.addProperty("message", "short string message for debugging");
JsonArray jsonErrors = new JsonArray();
for (String error : errors) {
jsonErrors.add(new JsonPrimitive(error));
}
jsonThis.add("errors", jsonErrors);
return jsonThis;
}Example 34
| Project: agile-itsm-master File: JSONUtil.java View source code |
public static Map<String, Object> convertJsonToMap(final String strData, final boolean convKeyToUpperCase) {
if (strData == null) {
return null;
}
final JsonParser parserJson = new JsonParser();
final JsonElement element = parserJson.parse(strData);
if (JsonObject.class.isInstance(element)) {
final JsonObject object = (JsonObject) element;
if (object != null) {
final Set<Map.Entry<String, JsonElement>> set = object.entrySet();
final Iterator<Map.Entry<String, JsonElement>> iterator = set.iterator();
final Map<String, Object> map = new HashMap<>();
while (iterator.hasNext()) {
final Map.Entry<String, JsonElement> entry = iterator.next();
String key = entry.getKey();
final JsonElement value = entry.getValue();
if (convKeyToUpperCase) {
if (key != null) {
key = key.toUpperCase();
}
}
if (!value.isJsonPrimitive()) {
if (value.isJsonArray()) {
map.put(key, JSONUtil.convertJsonArrayToCollection((JsonArray) value, convKeyToUpperCase));
} else {
map.put(key, JSONUtil.convertJsonToMap(value.toString(), convKeyToUpperCase));
}
} else {
map.put(key, value.getAsString());
}
}
return map;
}
}
if (JsonArray.class.isInstance(element)) {
final JsonArray array = (JsonArray) element;
final Map<String, Object> map = new HashMap<>();
map.put("ARRAY", JSONUtil.convertJsonArrayToCollection(array, convKeyToUpperCase));
return map;
}
return null;
}Example 35
| Project: AIDR-master File: DeserializeFilters.java View source code |
public JsonQueryList deserializeConstraints(final String queryString) {
Gson jsonObject = new GsonBuilder().serializeNulls().disableHtmlEscaping().serializeSpecialFloatingPointValues().create();
if (!StringUtils.isEmpty(queryString)) {
JsonParser parser = new JsonParser();
JsonObject obj = (JsonObject) parser.parse(queryString);
JsonArray constraintsArray = null;
if (obj.has("constraints")) {
// should always be true
constraintsArray = obj.get("constraints") != null ? obj.get("constraints").getAsJsonArray() : new JsonArray();
//logger.debug("constraints: " + constraintsArray);
}
JsonQueryList queryList = new JsonQueryList();
if (constraintsArray.size() > 0) {
for (int i = 0; i < constraintsArray.size(); i++) {
try {
JsonElement q = constraintsArray.get(i);
//System.out.println("constraint " + i + ": " + q);
GenericInputQuery constraint = jsonObject.fromJson(q, GenericInputQuery.class);
queryList.createConstraint(constraint);
} catch (Exception e) {
logger.error("Error in deserializing received constraints", e);
return null;
}
}
}
logger.debug("Output: deserialized queryList: " + queryList);
return queryList;
}
logger.debug("Output: deserialized queryList: null");
return null;
}Example 36
| Project: android-question-answer-app-master File: QuestionSerializer.java View source code |
@Override
public JsonElement serialize(final Question item, final Type type, final JsonSerializationContext context) {
final JsonObject object = new JsonObject();
object.addProperty("id", item.getId().toString());
object.addProperty("title", item.getTitle());
object.addProperty("body", item.getBody());
// image - don't know what I'm doing with this yet;
object.addProperty("author", item.getAuthor());
object.add("date", context.serialize(item.getDate()));
object.addProperty("upvotes", item.getUpvotes());
final JsonArray answerList = new JsonArray();
for (UUID aid : item.getAnswerList()) {
final JsonPrimitive answerId = new JsonPrimitive(aid.toString());
answerList.add(answerId);
}
object.add("answers", answerList);
final JsonArray commentList = new JsonArray();
for (UUID cid : item.getCommentList()) {
final JsonPrimitive answerId = new JsonPrimitive(cid.toString());
commentList.add(answerId);
}
object.add("comments", commentList);
return object;
}Example 37
| Project: AndroidMaterialDesignToolbar-master_modified-master File: NewsJsonUtils.java View source code |
/**
* 将获�到的json转�为新闻列表对象
* @param res
* @param value
* @return
*/
public static List<NewsBean> readJsonNewsBeans(String res, String value) {
List<NewsBean> beans = new ArrayList<NewsBean>();
try {
JsonParser parser = new JsonParser();
JsonObject jsonObj = parser.parse(res).getAsJsonObject();
JsonElement jsonElement = jsonObj.get(value);
if (jsonElement == null) {
return null;
}
JsonArray jsonArray = jsonElement.getAsJsonArray();
for (int i = 1; i < jsonArray.size(); i++) {
JsonObject jo = jsonArray.get(i).getAsJsonObject();
if (jo.has("skipType") && "special".equals(jo.get("skipType").getAsString())) {
continue;
}
if (jo.has("TAGS") && !jo.has("TAG")) {
continue;
}
if (!jo.has("imgextra")) {
NewsBean news = JsonUtils.deserialize(jo, NewsBean.class);
beans.add(news);
}
}
} catch (Exception e) {
LogUtils.e(TAG, "readJsonNewsBeans error", e);
}
return beans;
}Example 38
| Project: AntiqueAtlas-master File: TextureSetConfig.java View source code |
@Override
protected void loadData(JsonObject json, TextureSetMap data, int version) {
for (Entry<String, JsonElement> entry : json.entrySet()) {
String name = entry.getKey();
JsonArray array = entry.getValue().getAsJsonArray();
ResourceLocation[] textures = new ResourceLocation[array.size()];
for (int i = 0; i < array.size(); i++) {
String path = array.get(i).getAsString();
textures[i] = new ResourceLocation(path);
}
data.register(new TextureSet(name, textures));
Log.info("Loaded texture set %s with %d custom texture(s)", name, textures.length);
}
}Example 39
| Project: aokp-gerrit-master File: ParameterParserTest.java View source code |
@Test
public void testConvertFormToJson() throws BadRequestException {
JsonObject obj = ParameterParser.formToJson(ImmutableMap.of("message", new String[] { "this.is.text" }, "labels.Verified", new String[] { "-1" }, "labels.Code-Review", new String[] { "2" }, "a_list", new String[] { "a", "b" }), ImmutableSet.of("q"));
JsonObject labels = new JsonObject();
labels.addProperty("Verified", "-1");
labels.addProperty("Code-Review", "2");
JsonArray list = new JsonArray();
list.add(new JsonPrimitive("a"));
list.add(new JsonPrimitive("b"));
JsonObject exp = new JsonObject();
exp.addProperty("message", "this.is.text");
exp.add("labels", labels);
exp.add("a_list", list);
assertEquals(exp, obj);
}Example 40
| Project: ASSISTmentsDirect-master File: LoadWorkSheets.java View source code |
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String spreadsheetId = request.getParameter("spreadsheetId");
HttpSession session = request.getSession();
List<SpreadsheetEntry> spreadsheets = (List<SpreadsheetEntry>) session.getAttribute("spreadsheets");
for (SpreadsheetEntry spreadsheet : spreadsheets) {
if (spreadsheet.getId().equals(spreadsheetId)) {
try {
List<WorksheetEntry> worksheets = spreadsheet.getWorksheets();
session.setAttribute("worksheets", worksheets);
PrintWriter out = response.getWriter();
JsonArray jsonSheets = new JsonArray();
for (int i = 0; i < worksheets.size(); i++) {
JsonObject sheet = new JsonObject();
sheet.addProperty("id", worksheets.get(i).getId());
sheet.addProperty("name", worksheets.get(i).getTitle().getPlainText());
jsonSheets.add(sheet);
}
out.write(jsonSheets.toString());
out.flush();
out.close();
} catch (ServiceException e) {
e.printStackTrace();
}
}
}
}Example 41
| Project: asteria-3.0-master File: JsonLoader.java View source code |
/**
* 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;
}Example 42
| Project: ATLauncher-master File: PropertyMapSerializer.java View source code |
@Override
public JsonElement serialize(PropertyMap src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject out = new JsonObject();
for (String key : src.keySet()) {
JsonArray jsa = new JsonArray();
for (com.mojang.authlib.properties.Property p : src.get(key)) {
jsa.add(new JsonPrimitive(p.getValue()));
}
out.add(key, jsa);
}
return out;
}Example 43
| Project: bigbluebutton-master File: NewPermissionsSettingMessage.java View source code |
public static NewPermissionsSettingMessage fromJson(String message) {
JsonParser parser = new JsonParser();
JsonObject obj = (JsonObject) parser.parse(message);
if (obj.has("header") && obj.has("payload")) {
JsonObject header = (JsonObject) obj.get("header");
JsonObject payload = (JsonObject) obj.get("payload");
if (header.has("name")) {
String messageName = header.get("name").getAsString();
if (NEW_PERMISSIONS_SETTING.equals(messageName)) {
if (payload.has(Constants.MEETING_ID) && payload.has(Constants.USERS) && payload.has(Constants.PERMISSIONS)) {
String meetingID = payload.get(Constants.MEETING_ID).getAsString();
JsonObject permissions = (JsonObject) payload.get(Constants.PERMISSIONS);
Util util = new Util();
Map<String, Boolean> permissionsMap = util.extractPermission(permissions);
JsonArray users = (JsonArray) payload.get(Constants.USERS);
ArrayList<Map<String, Object>> usersList = util.extractUsers(users);
if (usersList != null && permissionsMap != null) {
return new NewPermissionsSettingMessage(meetingID, permissionsMap, usersList);
}
}
}
}
}
return null;
}Example 44
| Project: buck-master File: BuckQueryCommandHandler.java View source code |
@Override
protected void notifyLines(Key outputType, Iterable<String> lines) {
super.notifyLines(outputType, lines);
if (outputType == ProcessOutputTypes.STDOUT) {
List<String> targetList = new LinkedList<String>();
for (String outputLine : lines) {
if (!outputLine.isEmpty()) {
JsonElement jsonElement = new JsonParser().parse(outputLine);
if (jsonElement.isJsonArray()) {
JsonArray targets = jsonElement.getAsJsonArray();
for (JsonElement target : targets) {
targetList.add(target.getAsString());
}
}
}
}
actionsToExecute.apply(targetList);
}
}Example 45
| Project: bugsnag-eclipse-plugin-master File: JsonUtils.java View source code |
/**
* Get JSON string and convert to T (Object) you need
*
* @param json
* @return Object filled with JSON string data
*/
public static <T> T fromJson(String json, Class<T> cls) {
if (json == null || json.equals("")) {
return null;
}
Gson gson = create();
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(json);
// check if the Class type is array but the Json is an object
if (cls != null && cls.isArray() && element instanceof JsonArray == false) {
JsonArray jsonArray = new JsonArray();
jsonArray.add(element);
Type listType = new TypeToken<T>() {
}.getType();
return gson.fromJson(jsonArray, listType);
}
try {
return gson.fromJson(json, cls);
} catch (Exception e) {
return null;
}
}Example 46
| Project: C9MJ-master File: ExploreListPresenterImpl.java View source code |
@Override
public Publisher<ArrayList<ExploreListItemBean>> apply(JsonObject jsonObject) throws Exception {
for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
if (entry.getValue().isJsonArray()) {
JsonArray array = entry.getValue().getAsJsonArray();
ArrayList<ExploreListItemBean> list = new ArrayList<>();
for (JsonElement element : array) {
list.add((ExploreListItemBean) GsonHelper.parseJson(element, ExploreListItemBean.class));
}
return Flowable.just(list);
}
}
return null;
}Example 47
| Project: cdap-master File: WorkflowNodeThrowableCodec.java View source code |
@Override
public WorkflowNodeThrowable deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObj = json.getAsJsonObject();
String className = jsonObj.get("className").getAsString();
String message = jsonObj.get("message").getAsString();
JsonArray stackTraces = jsonObj.get("stackTraces").getAsJsonArray();
StackTraceElement[] stackTraceElements = context.deserialize(stackTraces, StackTraceElement[].class);
JsonElement cause = jsonObj.get("cause");
WorkflowNodeThrowable dfc = null;
if (cause != null) {
dfc = context.deserialize(cause, WorkflowNodeThrowable.class);
}
return new WorkflowNodeThrowable(className, message, stackTraceElements, dfc);
}Example 48
| Project: CIAPI.Java-master File: Type.java View source code |
@Override
public Type deserialize(JsonElement json, java.lang.reflect.Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Gson g = GsonHelper.gson(Type.class);
if (json.isJsonPrimitive()) {
Type t = new Type();
t.$ref = json.getAsString();
return t;
} else if (json.isJsonArray()) {
g = GsonHelper.gson();
JsonArray arr = json.getAsJsonArray();
Type t = g.fromJson(arr.get(1), Type.class);
return t;
} else {
Type t = g.fromJson(json, Type.class);
return t;
}
}Example 49
| Project: civilian-master File: KeyListSerializer.java View source code |
/**
* Serializes the KeyList.
*/
@Override
public JsonElement serialize(KeyList<?> keyList, Type typeOfSrc, JsonSerializationContext context) {
JsonArray array = new JsonArray();
int n = keyList.size();
for (int i = 0; i < n; i++) {
String text = keyList.getText(i);
Object value = keyList.getValue(i);
JsonObject element = new JsonObject();
element.addProperty("text", text);
element.add("value", context.serialize(value));
array.add(element);
}
return array;
}Example 50
| Project: Common-master File: NewsJsonUtils.java View source code |
/**
* 将获�到的json转�为新闻列表对象
*
* @param res
* @param value
* @return
*/
public static List<NewsEntity> readJsonDataBeans(String res, String value) {
List<NewsEntity> beans = new ArrayList<>();
try {
JsonParser parser = new JsonParser();
JsonObject jsonObj = parser.parse(res).getAsJsonObject();
JsonElement jsonElement = jsonObj.get(value);
if (jsonElement == null) {
return null;
}
JsonArray jsonArray = jsonElement.getAsJsonArray();
for (int i = 1; i < jsonArray.size(); i++) {
JsonObject jo = jsonArray.get(i).getAsJsonObject();
if (jo.has("skipType") && "special".equals(jo.get("skipType").getAsString())) {
continue;
}
if (jo.has("TAGS") && !jo.has("TAG")) {
continue;
}
NewsEntity news = JsonUtils.deserialize(jo, NewsEntity.class);
beans.add(news);
}
} catch (Exception e) {
}
return beans;
}Example 51
| Project: devfestnorte-app-master File: ManifestData.java View source code |
public void setFromDataFiles(JsonArray files) {
for (JsonElement file : files) {
String filename = file.getAsString();
Matcher matcher = Config.SESSIONS_PATTERN.matcher(filename);
if (matcher.matches()) {
sessionsFilename = filename;
majorVersion = Integer.parseInt(matcher.group(1));
minorVersion = Integer.parseInt(matcher.group(2));
} else {
dataFiles.add(file);
}
}
}Example 52
| Project: dextranet-master File: MicroBlogRSTest.java View source code |
@Test
public void testSimplePost() {
MicroBlogRS rs = getMicroBlogRS();
rs.post("micromessage");
JsonArray json = JsonUtil.parse((String) rs.get().getEntity()).getAsJsonArray();
assertEquals(1, json.size());
assertEquals("micromessage", json.get(0).getAsJsonObject().get("texto").getAsString());
assertEquals("autor", json.get(0).getAsJsonObject().get("autor").getAsString());
}Example 53
| Project: disqus-android-master File: ApplicationsUsageDeserializer.java View source code |
@Override
public Usage deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
// JSON element should be an array
if (json.isJsonArray()) {
// Create usage
Usage usage = new Usage();
// Iterate the array
for (JsonElement element : json.getAsJsonArray()) {
// Each element should be an array containing a date and int
if (element.isJsonArray() && element.getAsJsonArray().size() == 2) {
JsonArray jsonArray = element.getAsJsonArray();
Date date = context.deserialize(jsonArray.get(0), Date.class);
int count = jsonArray.get(1).getAsInt();
usage.put(date, count);
}
}
return usage;
}
return null;
}Example 54
| Project: DisqusSDK-Android-master File: ApplicationsUsageDeserializer.java View source code |
@Override
public Usage deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
// JSON element should be an array
if (json.isJsonArray()) {
// Create usage
Usage usage = new Usage();
// Iterate the array
for (JsonElement element : json.getAsJsonArray()) {
// Each element should be an array containing a date and int
if (element.isJsonArray() && element.getAsJsonArray().size() == 2) {
JsonArray jsonArray = element.getAsJsonArray();
Date date = context.deserialize(jsonArray.get(0), Date.class);
int count = jsonArray.get(1).getAsInt();
usage.put(date, count);
}
}
return usage;
}
return null;
}Example 55
| Project: disunity-master File: JsonTablePrinter.java View source code |
private JsonArray tableToJson(Table<Integer, Integer, Object> table, Gson gson) { JsonArray jsonTable = new JsonArray(); table.rowMap().forEach(( rk, r) -> { if (rk == 0) { return; } JsonObject jsonRow = new JsonObject(); table.columnMap().forEach(( ck, c) -> { String key = String.valueOf(table.get(0, ck)).toLowerCase(); Object value = table.get(rk, ck); jsonRow.add(key, gson.toJsonTree(value)); }); jsonTable.add(jsonRow); }); JsonObject jsonRoot = new JsonObject(); if (file != null) { jsonRoot.add("file", new JsonPrimitive(file.toString())); } return jsonTable; }
Example 56
| Project: EasyReader-master File: NewsJsonUtils.java View source code |
/**
* 将获�到的json转�为新闻列表对象
* @param res
* @param value
* @return
*/
public static List<NewsListBean.NewsBean> readJsonNewsBeans(String res, String value) {
List<NewsListBean.NewsBean> beans = new ArrayList<NewsListBean.NewsBean>();
try {
JsonParser parser = new JsonParser();
JsonObject jsonObj = parser.parse(res).getAsJsonObject();
JsonElement jsonElement = jsonObj.get(value);
if (jsonElement == null) {
return null;
}
JsonArray jsonArray = jsonElement.getAsJsonArray();
for (int i = 1; i < jsonArray.size(); i++) {
JsonObject jo = jsonArray.get(i).getAsJsonObject();
if (jo.has("skipType") && "special".equals(jo.get("skipType").getAsString())) {
continue;
}
if (jo.has("TAGS") && !jo.has("TAG")) {
continue;
}
if (!jo.has("imgextra")) {
NewsListBean.NewsBean news = JsonUtils.deserialize(jo, NewsListBean.NewsBean.class);
beans.add(news);
}
}
} catch (Exception e) {
}
return beans;
}Example 57
| Project: eclipse3-master File: TypeHierarchyProcessor.java View source code |
public void process(JsonObject resultObject, RequestError requestError) {
if (resultObject != null) {
try {
JsonArray typeHierarchyItemsArray = resultObject.get("hierarchyItems") != null ? resultObject.get("hierarchyItems").getAsJsonArray() : null;
// construct type hierarchy item list and notify listener
consumer.computedHierarchy(TypeHierarchyItem.fromJsonArray(typeHierarchyItemsArray));
} catch (Exception exception) {
requestError = generateRequestError(exception);
}
}
if (requestError != null) {
consumer.onError(requestError);
}
}Example 58
| Project: enviroCar-app-master File: TermsOfUseListSerializer.java View source code |
@Override
public List<TermsOfUse> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
// Get the json element as array
JsonArray array = json.getAsJsonObject().get(TermsOfUse.KEY_TERMSOFUSE).getAsJsonArray();
// Iterate over each json object
List<TermsOfUse> res = new ArrayList<>(array.size());
for (int i = 0, size = array.size(); i < size; i++) {
// and deserialize the json object.
res.add(context.deserialize(array.get(i), TermsOfUse.class));
}
return res;
}Example 59
| Project: EveryXDay-master File: CommonRequestWrapWithType.java View source code |
@Override
public void setResponseObject(CommonResponseBody<T> responseBody, String str, Gson gson) {
try {
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(str).getAsJsonArray();
List<T> lst = new ArrayList<T>();
for (final JsonElement json : array) {
T entity = gson.fromJson(json, getBeanType());
lst.add(entity);
}
responseBody.setList(lst);
} catch (Exception e) {
}
}Example 60
| Project: expenditures-master File: PrintService.java View source code |
@Override
protected void createServiceRequest(final Unit financer, final JsonElement beneficiaryConfig) {
final JsonArray array = beneficiaryConfig.getAsJsonArray();
for (final JsonElement e : array) {
final JsonObject o = e.getAsJsonObject();
final DomainObject domainObject = FenixFramework.getDomainObject(o.get("beneficiaryId").getAsString());
final Beneficiary beneficiary = beneficiaryFor(domainObject);
if (beneficiary != null) {
final JsonElement maxValueString = o.get("maxValue");
final Money maxValue = maxValueString == null || maxValueString.isJsonNull() ? Money.ZERO : new Money(maxValueString.getAsString());
if (maxValue.isPositive() && !hasActiveBillable(financer, beneficiary)) {
final Billable billable = new Billable(this, financer, beneficiary);
final JsonObject configuration = new JsonObject();
configuration.addProperty("maxValue", maxValue.exportAsString());
final String configString = configuration.toString();
billable.setConfiguration(configString);
billable.log("Subscribed service " + getTitle() + " for unit " + financer.getPresentationName() + " to user " + beneficiary.getPresentationName() + " with configuration " + configString);
}
}
}
}Example 61
| Project: fiery-master File: PutBizLog.java View source code |
@RequestMapping(value = "/log/bizlog/put", method = RequestMethod.POST)
@ResponseBody
public ResponseJson appendLog(@RequestParam(value = "contents", required = false) String contents) {
ResponseJson result = new ResponseJson();
if (contents == null || contents.length() == 0) {
result.setCode(401);
result.setMsg("Plasee set the contents paramter!");
return result;
}
//split the json to by \n
String[] contentslist = contents.split("\n");
if (contentslist.length <= 0) {
result.setCode(405);
result.setMsg("contents paramter format Wrong!");
return result;
}
for (int i = 0; i < contentslist.length; i++) {
String jsonstr = contentslist[i].trim();
JsonParser valueParse = new JsonParser();
try {
JsonArray valueArr = (JsonArray) valueParse.parse(jsonstr);
bizLogProcessor.insertDataQueue(valueArr);
} catch (Exception e) {
log.error("parser json wrong:" + jsonstr);
}
}
return result;
}Example 62
| Project: flatpack-java-master File: FlatPackEntityMergeTest.java View source code |
@Test
public void test() throws IOException {
Employee e1 = makeEmployee();
Employee e2 = makeEmployee();
JsonElement j1 = flatpack.getPacker().pack(FlatPackEntity.entity(e1));
JsonElement j2 = flatpack.getPacker().pack(FlatPackEntity.entity(e2));
JsonObject merged = FlatPackEntityMerge.merge(j2, j1).getAsJsonObject();
assertEquals(2, merged.entrySet().size());
assertEquals(e1.getUuid().toString(), merged.get("value").getAsString());
JsonArray employeeArray = merged.get("data").getAsJsonObject().get("employee").getAsJsonArray();
assertEquals(2, employeeArray.size());
FlatPackEntity<Employee> entity = flatpack.getUnpacker().<Employee>unpack(Employee.class, merged, null);
Employee u1 = entity.getValue();
assertEquals(e1, u1);
assertEquals(2, entity.getExtraEntities().size());
}Example 63
| Project: gargl-master File: JsonUtils.java View source code |
private static JsonElement search(Queue<JsonElement> queue, String elementName) {
JsonElement ret = null;
while (queue.size() > 0) {
JsonElement element = queue.poll();
if (element.isJsonObject()) {
JsonObject object = element.getAsJsonObject();
Set<Entry<String, JsonElement>> members = object.entrySet();
for (Entry<String, JsonElement> member : members) {
if (member.getKey().equals(elementName)) {
return member.getValue();
} else {
queue.add(member.getValue());
}
}
} else if (element.isJsonArray()) {
JsonArray array = element.getAsJsonArray();
for (JsonElement array_element : array) {
queue.add(array_element);
}
}
}
return ret;
}Example 64
| Project: gerrit-master File: ParameterParserTest.java View source code |
@Test
public void convertFormToJson() throws BadRequestException {
JsonObject obj = ParameterParser.formToJson(ImmutableMap.of("message", new String[] { "this.is.text" }, "labels.Verified", new String[] { "-1" }, "labels.Code-Review", new String[] { "2" }, "a_list", new String[] { "a", "b" }), ImmutableSet.of("q"));
JsonObject labels = new JsonObject();
labels.addProperty("Verified", "-1");
labels.addProperty("Code-Review", "2");
JsonArray list = new JsonArray();
list.add(new JsonPrimitive("a"));
list.add(new JsonPrimitive("b"));
JsonObject exp = new JsonObject();
exp.addProperty("message", "this.is.text");
exp.add("labels", labels);
exp.add("a_list", list);
assertEquals(exp, obj);
}Example 65
| Project: gobblin-master File: TeradataSource.java View source code |
public Extractor<JsonArray, JsonElement> getExtractor(WorkUnitState state) throws IOException { Extractor<JsonArray, JsonElement> extractor = null; try { extractor = new TeradataExtractor(state).build(); } catch (ExtractPrepareException e) { log.error("Failed to prepare extractor: error - {}", e.getMessage()); throw new IOException(e); } return extractor; }
Example 66
| Project: GroceryGo-master File: JSONParser.java View source code |
public JsonArray getJSONFromUrl(String url) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JsonArray JsonParser jsonParser = new JsonParser(); jObj = jsonParser.parse(json).getAsJsonArray(); return jObj; }
Example 67
| Project: hapi-fhir-master File: CopyOperation.java View source code |
@Override
public JsonElement apply(JsonElement original) {
JsonElement result = duplicate(original);
JsonElement item = path.head().navigate(result);
JsonElement data = mySourcePath.head().navigate(original);
if (item.isJsonObject()) {
item.getAsJsonObject().add(path.tail(), data);
} else if (item.isJsonArray()) {
JsonArray array = item.getAsJsonArray();
int index = (path.tail().equals("-")) ? array.size() : Integer.valueOf(path.tail());
List<JsonElement> temp = new ArrayList<JsonElement>();
Iterator<JsonElement> iter = array.iterator();
while (iter.hasNext()) {
JsonElement stuff = iter.next();
iter.remove();
temp.add(stuff);
}
temp.add(index, data);
for (JsonElement stuff : temp) {
array.add(stuff);
}
}
return result;
}Example 68
| Project: IBM-Ready-App-for-Telecommunications-master File: WifiHotspotUtils.java View source code |
public static List<WifiHotspotFlat> parseAndOffsetHotspots(String stringResponse, GeoJsonPoint userLocation) {
List<WifiHotspotFlat> hotspots = new ArrayList<WifiHotspotFlat>();
JsonArray array = new JsonParser().parse(stringResponse).getAsJsonObject().getAsJsonArray("rows");
Gson gson = new Gson();
WifiHotspot temp;
if (array.size() > 0) {
for (JsonElement elem : array) {
JsonElement e = elem.getAsJsonObject().get("doc");
temp = gson.fromJson(e, WifiHotspot.class);
temp.setGeometry(WifiHotspotUtils.randomLocationOffset(userLocation.getLongitude(), userLocation.getLatitude(), Constants.GEO_RETURN_RADIUS));
hotspots.add(temp.flatten());
}
}
return hotspots;
}Example 69
| Project: iosched-master File: ManifestData.java View source code |
public void setFromDataFiles(JsonArray files) {
for (JsonElement file : files) {
String filename = file.getAsString();
Matcher matcher = Config.SESSIONS_PATTERN.matcher(filename);
if (matcher.matches()) {
sessionsFilename = filename;
majorVersion = Integer.parseInt(matcher.group(1));
minorVersion = Integer.parseInt(matcher.group(2));
} else {
dataFiles.add(file);
}
}
}Example 70
| Project: iot-java-master File: CancelRequestHandler.java View source code |
/**
* This method handles the cancel request messages from IBM Watson IoT Platform
*/
@Override
protected void handleRequest(JsonObject jsonRequest, String topic) {
JsonArray fields;
JsonObject d = (JsonObject) jsonRequest.get("d");
if (d != null) {
fields = (JsonArray) d.get("data");
if (fields != null) {
ObserveRequestHandler observe = getObserveRequestHandler(getDMClient());
if (observe != null) {
observe.cancel(fields);
}
}
}
JsonObject response = new JsonObject();
response.add("reqId", jsonRequest.get("reqId"));
response.add("rc", new JsonPrimitive(ResponseCode.DM_SUCCESS.getCode()));
respond(response);
}Example 71
| Project: JAnGLE-master File: JsonSerializer.java View source code |
@Override
public LevelData deserialize(Level level, String data) {
JsonObject o = parser.parse(data).getAsJsonObject();
JsonArray layers = o.remove("layers").getAsJsonArray();
LayerData[] lDataLayers = new LayerData[layers.size()];
for (int i = 0; i < layers.size(); i++) {
Layer layer = level.getLayers().get(i);
JsonObject ldat = layers.get(i).getAsJsonObject();
lDataLayers[i] = new LayerData(ldat.get("name").getAsString(), gson.fromJson(ldat.get("data"), layer.getExportDataClass()));
}
LevelData lData = gson.fromJson(o, LevelData.class);
lData.layers = lDataLayers;
return lData;
}Example 72
| Project: jcloudscale-master File: JsonListTypeAdapter.java View source code |
@Override
public JsonElement serialize(List<?> object, TypeMetadata<JsonElement> typeMetadata) {
JsonArray jsonArray = new JsonArray();
TypeAdapter typeAdapter = typeMetadata.getTypeParameterTypeAdapters().get(0);
for (Object item : object) {
JsonElement jsonElement = (JsonElement) typeAdapter.serialize(item, typeMetadata);
jsonArray.add(jsonElement);
}
return jsonArray;
}Example 73
| Project: Jest-master File: HistogramAggregation.java View source code |
private void parseBuckets(JsonArray bucketsSource) {
for (JsonElement bucketv : bucketsSource) {
JsonObject bucket = bucketv.getAsJsonObject();
Histogram histogram = new Histogram(bucket, bucket.get(String.valueOf(KEY)).getAsLong(), bucket.get(String.valueOf(DOC_COUNT)).getAsLong());
histograms.add(histogram);
}
}Example 74
| Project: js-android-sdk-master File: ReportLookupTypeAdapterFactory.java View source code |
@Override
protected JsonElement afterRead(JsonElement deserialized) {
JsonObject jsonObject = deserialized.getAsJsonObject();
JsonObject resources = jsonObject.getAsJsonObject("resources");
if (resources != null) {
JsonArray resourceArray = resources.getAsJsonArray("resource");
jsonObject.remove("resources");
jsonObject.add("resources", resourceArray);
}
return jsonObject;
}Example 75
| Project: js-test-driver-master File: JsTestDriverModuleTest.java View source code |
public void testGetActionRunnerWithoutXmlPrinter() throws Exception {
FlagsImpl flags = new FlagsImpl();
Guice.createInjector(new TestResultPrintingModule(), new DebugModule(false), new JsTestDriverModule(flags, Collections.<FileInfo>emptySet(), "http://foo", "http://foo", System.out, new BasePaths(new File("")), 2 * 60 * 60, Collections.<FileInfo>emptyList(), Collections.<FileInfo>emptyList(), new JsonArray())).getInstance(ActionRunner.class);
}Example 76
| Project: juxta-service-master File: AlignmentSerializer.java View source code |
public JsonElement serialize(Alignment align, Type typeOfSrc, JsonSerializationContext context) {
JsonObject name = new JsonObject();
name.addProperty("namespace", align.getName().getNamespace().toString());
name.addProperty("localName", align.getName().getLocalName());
JsonArray annotations = new JsonArray();
for (AlignedAnnotation anno : align.getAnnotations()) {
JsonObject range = new JsonObject();
range.addProperty("start", anno.getRange().getStart());
range.addProperty("end", anno.getRange().getEnd());
JsonObject annoObj = new JsonObject();
annoObj.addProperty("id", anno.getId());
annoObj.addProperty("witnessId", anno.getWitnessId());
annoObj.add("range", range);
annoObj.addProperty("fragment", anno.getFragment());
annotations.add(annoObj);
}
JsonObject obj = new JsonObject();
obj.addProperty("id", align.getId());
obj.add("name", name);
obj.addProperty("editDistance", align.getEditDistance());
obj.add("annotations", annotations);
return obj;
}Example 77
| Project: karyon-master File: DataTableHelper.java View source code |
public static JsonObject buildOutput(TableViewResource tableViewResource, MultivaluedMap<String, String> queryParams) {
JsonObject output = new JsonObject();
applyQueryParams(tableViewResource, queryParams);
JsonArray data = tableViewResource.getData();
final String sEcho = queryParams.getFirst("sEcho");
output.addProperty("iTotalRecords", tableViewResource.getTotalNumOfRecords());
output.addProperty("iTotalDisplayRecords", tableViewResource.getFilteredNumOfRecords());
output.addProperty("sEcho", sEcho);
output.add("aaData", data);
return output;
}Example 78
| Project: LookLook-master File: NewsJsonUtils.java View source code |
/**
* 将获�到的json转�为新闻列表对象
* @param res
* @param value
* @return
*/
public static List<NewsBean> readJsonNewsBeans(String res, String value) {
List<NewsBean> beans = new ArrayList<NewsBean>();
try {
JsonParser parser = new JsonParser();
JsonObject jsonObj = parser.parse(res).getAsJsonObject();
JsonElement jsonElement = jsonObj.get(value);
if (jsonElement == null) {
return null;
}
JsonArray jsonArray = jsonElement.getAsJsonArray();
for (int i = 1; i < jsonArray.size(); i++) {
JsonObject jo = jsonArray.get(i).getAsJsonObject();
if (jo.has("skipType") && "special".equals(jo.get("skipType").getAsString())) {
continue;
}
if (jo.has("TAGS") && !jo.has("TAG")) {
continue;
}
if (!jo.has("imgextra")) {
NewsBean news = JsonUtils.deserialize(jo, NewsBean.class);
beans.add(news);
}
}
} catch (Exception e) {
}
return beans;
}Example 79
| Project: Matekarte-master File: DealersListDeserializer.java View source code |
public DealersList deserialize(JsonElement element, Type arg1, JsonDeserializationContext context) throws JsonParseException {
JsonObject tempJsonObject = element.getAsJsonObject();
List<Dealer> tempDealers = new ArrayList<Dealer>();
for (Entry<String, JsonElement> entry : tempJsonObject.entrySet()) {
String tmpId = entry.getKey();
JsonElement tmpValue = entry.getValue();
JsonArray tmpAsJsonArray = tmpValue.getAsJsonArray();
String tmpName = tmpAsJsonArray.get(0).getAsString();
double tmpLat = tmpAsJsonArray.get(1).getAsDouble();
double tmpLon = tmpAsJsonArray.get(2).getAsDouble();
Dealer tempDealer = new Dealer();
tempDealer.setId(tmpId);
tempDealer.setName(tmpName);
tempDealer.setLatitude(tmpLat);
tempDealer.setLongitude(tmpLon);
tempDealers.add(tempDealer);
}
return new DealersList(tempDealers);
}Example 80
| Project: mdmconnectors-master File: StagingExecutorTest.java View source code |
@Test
public void execute() {
log.info("Listing Domain DataSources...");
ICommand tenantCommand = new CommandListDatasource(MDMTestingConstants.SUBDOMAIN);
EnvelopeVO envelope = connection.executeCommand(tenantCommand);
assertNotNull("Hits result should not be null", envelope.getHits());
log.info(String.format("Found %s hits.", envelope.getHits().size()));
for (GenericVO vo : envelope.getHits()) {
log.info("Row: " + vo);
}
log.info("Staging data...");
JsonArray stagingArray = new JsonArray();
JsonObject testObject = new JsonObject();
testObject.addProperty("nome", "Bruno-Java Client");
stagingArray.add(testObject);
CommandPostStaging staging = new CommandPostStaging(MDMRestAuthentication.getInstance().getAuthVO().get_mdmTenantId(), MDMRestAuthentication.getInstance().getAuthVO().get_mdmDataSourceId(), "mdm_rest_client_test", stagingArray);
EnvelopeVO executeCommand = connection.executeCommand(staging);
log.info(executeCommand);
}Example 81
| Project: meep-server-historical-master File: Locations.java View source code |
/**
*
*/
public static void update(JsonArray body) {
if (body != null && body.isJsonArray()) {
List<UserLocationDTO> userLocationDTOs = UserLocationAssembler.userLocationDTOsWithJsonArray(body);
validation.valid(userLocationDTOs);
if (validation.hasErrors()) {
for (Error error : validation.errors()) {
Logger.debug(error.getKey() + " : " + error.message());
}
error(400, "Validation Errors");
}
// Update
if (userLocationDTOs != null) {
UserDTO currentUserDTO = getAuthorisedUserDTO();
List<UserLocationDTO> createdUserLocations = UserLocationAssembler.createUserLocations(userLocationDTOs, currentUserDTO);
// Publish location to other users
LocationStreamHelper.publishNewUserLocations(createdUserLocations, currentUserDTO);
renderJSON(createdUserLocations);
}
}
badRequest();
}Example 82
| Project: ms-nos-master File: ThreadSafeGson.java View source code |
@Override
public JsonElement serialize(Cloud src, Type typeOfSrc, JsonSerializationContext context) {
final JsonObject res = new JsonObject();
res.add("iden", context.serialize(src.getIden()));
final JsonArray idens = new JsonArray();
for (final LocalAgent agent : src.getLocalAgents()) {
idens.add(context.serialize(agent.getIden()));
}
res.add("agents", idens);
;
return res;
}Example 83
| Project: MvpApp-master File: GsonHelper.java View source code |
/**
* 将json数�转化为实体列表数�
* @param jsonData jsonå—符串
* @param entityClass 类型
* @return 实体列表
*/
public static <T> List<T> convertEntities(String jsonData, Class<T> entityClass) {
List<T> entities = new ArrayList<>();
try {
JsonArray jsonArray = sJsonParser.parse(jsonData).getAsJsonArray();
for (JsonElement element : jsonArray) {
entities.add(sGson.fromJson(element, entityClass));
}
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
return entities;
}Example 84
| Project: MvpBase-master File: NewsJsonUtils.java View source code |
/**
* 将获�到的json转�为新闻列表对象
* @param res
* @param value
* @return
*/
public static List<DataBean> readJsonDataBeans(String res, String value) {
List<DataBean> beans = new ArrayList<DataBean>();
try {
JsonParser parser = new JsonParser();
JsonObject jsonObj = parser.parse(res).getAsJsonObject();
JsonElement jsonElement = jsonObj.get(value);
if (jsonElement == null) {
return null;
}
JsonArray jsonArray = jsonElement.getAsJsonArray();
for (int i = 1; i < jsonArray.size(); i++) {
JsonObject jo = jsonArray.get(i).getAsJsonObject();
if (jo.has("skipType") && "special".equals(jo.get("skipType").getAsString())) {
continue;
}
if (jo.has("TAGS") && !jo.has("TAG")) {
continue;
}
if (!jo.has("imgextra")) {
DataBean news = JsonUtils.deserialize(jo, DataBean.class);
beans.add(news);
}
}
} catch (Exception e) {
}
return beans;
}Example 85
| Project: myLazyClock-master File: SmartEdtGroupData.java View source code |
public void reloadData() throws IOException {
Map<String, String> urlParameters = new HashMap<String, String>();
urlParameters.put("getGroup", String.valueOf(this.groupId));
urlParameters.put("bdd0", "");
JsonElement root = JsonConverter.getJson(urlParameters).getAsJsonArray().get(0);
JsonArray bdd = root.getAsJsonObject().get("bdds").getAsJsonArray();
/*
Array content : teachers, rooms, group, course name, course category
Mapped in bdd array from index 0 to 4 (5th is useless)
*/
List<String> mapId = Arrays.asList("teachers", "rooms", "groups", "courseNames", "courseCategories");
for (int i = 0; i < mapId.size(); i++) {
// Constant lenght, don't use last bdd array case
JsonElement bddElement = bdd.get(i);
JsonArray elements = bddElement.getAsJsonObject().get("values").getAsJsonArray();
HashMap<Integer, String> elementsMap = new HashMap<>();
for (JsonElement element : elements) {
int elementId = element.getAsJsonObject().get("id").getAsInt();
String elementName = element.getAsJsonObject().get("name").getAsString();
elementsMap.put(elementId, elementName);
}
this.data.put(mapId.get(i), elementsMap);
}
}Example 86
| Project: openseedbox-master File: IsohuntSearchPlugin.java View source code |
@Override
public List<PluginSearchResult> doSearch(String terms) {
List<PluginSearchResult> ret = new ArrayList<PluginSearchResult>();
HttpResponse res = WS.url("http://ca.isohunt.com/js/json.php?ihq=%s&rows=20&sort=seeds", terms).get();
if (res.getJson() != null) {
JsonObject itemsObject = res.getJson().getAsJsonObject().getAsJsonObject("items");
if (itemsObject != null) {
JsonArray items = itemsObject.getAsJsonArray("list");
for (JsonElement i : items) {
JsonObject it = i.getAsJsonObject();
PluginSearchResult psr = new PluginSearchResult();
psr.setTorrentName(Util.stripHtml(it.get("title").getAsString()));
psr.setTorrentUrl(it.get("enclosure_url").getAsString());
psr.setCurrentPeers(it.get("leechers").getAsString());
psr.setCurrentSeeders(it.get("Seeds").getAsString());
psr.setFileSize(Util.getBestRate(it.get("length").getAsLong()));
ret.add(psr);
}
}
}
return ret;
}Example 87
| Project: osmeditor4android-master File: PositionSerializer.java View source code |
/**
* Required to handle the special case where the altitude might be a Double.NaN, which isn't a
* valid double value as per JSON specification.
*
* @param src A {@link Position} defined by a longitude, latitude, and optionally, an
* altitude.
* @param typeOfSrc Common superinterface for all types in the Java.
* @param context Context for deserialization that is passed to a custom deserializer during
* invocation of its {@link com.google.gson.JsonDeserializer#deserialize(JsonElement, Type,
* com.google.gson.JsonDeserializationContext)} method.
* @return a JsonArray containing the raw coordinates.
* @since 1.0.0
*/
@Override
public JsonElement serialize(Position src, Type typeOfSrc, JsonSerializationContext context) {
JsonArray rawCoordinates = new JsonArray();
rawCoordinates.add(new JsonPrimitive(src.getLongitude()));
rawCoordinates.add(new JsonPrimitive(src.getLatitude()));
// Includes altitude
if (src.hasAltitude()) {
rawCoordinates.add(new JsonPrimitive(src.getAltitude()));
}
return rawCoordinates;
}Example 88
| Project: our-alliance-android-master File: JsonWrapperAdapter.java View source code |
@Override
public JsonWrapper<Wrapped> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonWrapper<Wrapped> wrapper = newAdapter();
JsonObject object = json.getAsJsonObject();
if (wrapper.isType(object.get(JsonWrapper.TYPE).getAsString())) {
JsonArray dataList = object.getAsJsonArray(JsonWrapper.DATA);
if (dataList.size() == object.get(JsonWrapper.COUNT).getAsInt()) {
for (int i = 0; i < dataList.size(); i++) {
Wrapped newWrapped = elementToObject(dataList.get(i));
Timber.d("imported: " + newWrapped);
wrapper.add(newWrapped);
}
}
}
return wrapper;
}Example 89
| Project: platform_build-master File: BuckQueryCommandHandler.java View source code |
@Override
protected void notifyLines(Key outputType, Iterable<String> lines) {
super.notifyLines(outputType, lines);
if (outputType == ProcessOutputTypes.STDOUT) {
List<String> targetList = new LinkedList<String>();
for (String outputLine : lines) {
if (!outputLine.isEmpty()) {
JsonElement jsonElement = new JsonParser().parse(outputLine);
if (jsonElement.isJsonArray()) {
JsonArray targets = jsonElement.getAsJsonArray();
for (JsonElement target : targets) {
targetList.add(target.getAsString());
}
}
}
}
actionsToExecute.apply(targetList);
}
}Example 90
| Project: ps-framework-master File: JSONDescriptionHelper.java View source code |
public static JsonElement generateJsonDescription() {
// base object
JsonObject object = new JsonObject();
// get processes
List<AbstractProcess> processes = ProcessRepository.getInstance().getProcesses();
JsonArray processesArray = new JsonArray();
object.add("processes", processesArray);
// list details for each
for (AbstractProcess process : processes) {
JsonObject processObject = new JsonObject();
processesArray.add(processObject);
processObject.addProperty("identifier", process.getIdentifier());
List<Metadata> pMdList = process.getMetadata();
if (pMdList != null) {
for (Metadata md : pMdList) {
processObject.addProperty(md.getKey(), md.getValue());
}
}
JsonArray inputsArray = new JsonArray();
processObject.add("inputs", inputsArray);
for (String inputIdentifier : process.getInputIdentifiers()) {
JsonObject inputObject = new JsonObject();
inputsArray.add(inputObject);
inputObject.addProperty("identifier", inputIdentifier);
DataDescription dataDesc = process.getInputDataDescription(inputIdentifier);
inputObject.addProperty("type", dataDesc.getType().getSimpleName().toLowerCase());
List<Metadata> mdList = process.getInputMetadata(inputIdentifier);
if (mdList != null) {
for (Metadata md : mdList) {
inputObject.addProperty(md.getKey(), md.getValue());
}
}
}
JsonArray outputsArray = new JsonArray();
processObject.add("outputs", outputsArray);
for (String outputIdentifier : process.getOutputIdentifiers()) {
JsonObject outputObject = new JsonObject();
outputsArray.add(outputObject);
outputObject.addProperty("identifier", outputIdentifier);
DataDescription dataDesc = process.getOutputDataDescription(outputIdentifier);
outputObject.addProperty("type", dataDesc.getType().getSimpleName().toLowerCase());
List<Metadata> mdList = process.getOutputMetadata(outputIdentifier);
if (mdList != null) {
for (Metadata md : mdList) {
outputObject.addProperty(md.getKey(), md.getValue());
}
}
}
}
// all done
return object;
}Example 91
| Project: remusic-master File: MusicFileDownInfoGet.java View source code |
@Override
public void run() {
try {
JsonArray jsonArray = HttpUtil.getResposeJsonObject(BMA.Song.songInfo(id)).get("songurl").getAsJsonObject().get("url").getAsJsonArray();
int len = jsonArray.size();
MusicFileDownInfo musicFileDownInfo = null;
for (int i = len - 1; i > -1; i--) {
int bit = Integer.parseInt(jsonArray.get(i).getAsJsonObject().get("file_bitrate").toString());
if (bit == downloadBit) {
musicFileDownInfo = MainApplication.gsonInstance().fromJson(jsonArray.get(i), MusicFileDownInfo.class);
} else if (bit < downloadBit && bit >= 64) {
musicFileDownInfo = MainApplication.gsonInstance().fromJson(jsonArray.get(i), MusicFileDownInfo.class);
}
}
synchronized (this) {
if (musicFileDownInfo != null) {
arrayList.put(p, musicFileDownInfo);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}Example 92
| Project: sandbox-master File: ColorTypeHandlerTest.java View source code |
@Test
public void testDeserializeArray() {
JsonArray array = new Gson().fromJson("[12, 34, 56, 78]", JsonArray.class);
PersistedData data = new GsonPersistedDataArray(array);
Color color = handler.deserialize(data, deserializationContext);
Assert.assertEquals(12, color.r());
Assert.assertEquals(34, color.g());
Assert.assertEquals(56, color.b());
Assert.assertEquals(78, color.a());
}Example 93
| Project: sonar-gerrit-plugin-master File: GerritSshFacade.java View source code |
@Override
protected void fillListFilesFomGerrit() throws GerritPluginException {
try {
String rawJsonString = getGerritConnector().listFiles();
JsonArray files = new JsonParser().parse(rawJsonString.split("\r?\n")[0]).getAsJsonObject().getAsJsonObject("currentPatchSet").getAsJsonArray("files");
for (JsonElement jsonElement : files) {
String fileName = jsonElement.getAsJsonObject().get("file").getAsString();
if (COMMIT_MSG.equals(fileName)) {
continue;
}
JsonObject jsonObject = jsonElement.getAsJsonObject();
if (jsonObject.has("type") && isMarkAsDeleted(jsonObject)) {
LOG.debug("[GERRIT PLUGIN] File is marked as deleted, won't comment.");
continue;
}
addFile(fileName);
}
} catch (IOException e) {
throw new GerritPluginException(ERROR_LISTING, e);
}
}Example 94
| Project: swellrt-master File: ServiceData.java View source code |
public static ServiceData[] arrayFromJson(String json, Class<? extends ServiceData[]> classOf) throws JsonParseException {
ServiceData[] object = null;
JsonElement element = jsonParser.parse(json);
if (element == null)
throw new JsonParseException("Element is null");
object = gson.fromJson(element, classOf);
JsonArray array = element.getAsJsonArray();
for (int i = 0; i < object.length && i < array.size(); i++) {
object[i].set(array.get(i).getAsJsonObject());
}
return object;
}Example 95
| Project: taylorswift-master File: RedditParser.java View source code |
public static String find(String s) {
String title = "none";
String urlstring = s;
urlstring = urlstring + ".json";
try {
/*
URL url = new URL(urlstring);
URLConnection urlc = url.openConnection();
urlc.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
urlc.addRequestProperty("User-Agent", "Mozilla");
urlc.connect();
Scanner scan = new Scanner(urlc.getInputStream());
String jsonstring = "";
while(scan.hasNext()){
jsonstring += scan.next() + " ";
}
scan.close();
*/
String jsonstring = URLTitles.readUrl(urlstring);
Gson gson = new GsonBuilder().create();
JsonArray json = gson.fromJson(jsonstring, JsonElement.class).getAsJsonArray();
JsonObject first = json.get(0).getAsJsonObject();
JsonObject data = first.get("data").getAsJsonObject();
JsonArray children = data.get("children").getAsJsonArray();
JsonObject info = children.get(0).getAsJsonObject();
JsonObject infodata = info.get("data").getAsJsonObject();
int numComments = infodata.get("num_comments").getAsInt();
String created = new Date((long) infodata.get("created_utc").getAsDouble() * 1000).toGMTString();
String subreddit = infodata.get("subreddit").getAsString();
String postTitle = URLTitles.makeClean(infodata.get("title").getAsString());
String link = "";
if (!infodata.get("domain").getAsString().startsWith("self.")) {
link = "URL: " + infodata.get("url").getAsString() + " | ";
}
title = String.format("/r/%s | 2%s | %sComments: %d | Created %s", subreddit, postTitle, link, numComments, created);
return title;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
title = "Could not find info";
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return title;
}Example 96
| Project: teamcity-plugins-master File: GitHubPullRequestsTypeAdapter.java View source code |
@Override
public GitHubPullRequests deserialize(JsonElement json, Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
JsonArray jsonArray = json.getAsJsonArray();
List<GitHubPullRequest> pullRequests = FluentIterable.from(jsonArray).transform(new Function<JsonElement, GitHubPullRequest>() {
@Override
public GitHubPullRequest apply(JsonElement input) {
return context.deserialize(input, GitHubPullRequest.class);
}
}).toImmutableList();
GitHubPullRequests gitHubPullRequests = new GitHubPullRequests();
gitHubPullRequests.setPullRequests(pullRequests);
return gitHubPullRequests;
}Example 97
| Project: TeleCafe-master File: Services.java View source code |
public static GeolocalizacionOSMResponse localizarPedidoPorCalle(String calle) {
Client client = Client.create();
WebResource webResource = client.resource("http://nominatim.openstreetmap.org/search.php");
MultivaluedMap queryParams = new MultivaluedMapImpl();
queryParams.add("q", calle);
queryParams.add("format", "json");
ClientResponse response = webResource.queryParams(queryParams).get(ClientResponse.class);
GeolocalizacionOSMResponse localizacion = new GeolocalizacionOSMResponse();
if (response.getStatus() == 200) {
String respuesta = response.getEntity(String.class);
JsonElement json = new JsonParser().parse(respuesta);
JsonArray array = json.getAsJsonArray();
Iterator iterator = array.iterator();
while (iterator.hasNext()) {
JsonElement json2 = (JsonElement) iterator.next();
String jsonparseado = json2.toString();
jsonparseado = jsonparseado.replace("class", "clase");
Gson gson = new Gson();
localizacion = gson.fromJson(jsonparseado, GeolocalizacionOSMResponse.class);
break;
}
}
return localizacion;
}Example 98
| Project: Terasology-master File: ColorTypeHandlerTest.java View source code |
@Test
public void testDeserializeArray() {
JsonArray array = new Gson().fromJson("[12, 34, 56, 78]", JsonArray.class);
PersistedData data = new GsonPersistedDataArray(array);
Color color = handler.deserialize(data, deserializationContext);
Assert.assertEquals(12, color.r());
Assert.assertEquals(34, color.g());
Assert.assertEquals(56, color.b());
Assert.assertEquals(78, color.a());
}Example 99
| Project: TflTravelAlerts-master File: SparseArrayDeserializer.java View source code |
@Override
public SparseArray<?> deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
Type[] parameterizedTypes = ((ParameterizedType) type).getActualTypeArguments();
Type parameterizedType = parameterizedTypes[0];
JsonArray jsonKeys = json.getAsJsonObject().getAsJsonArray("keys");
int[] keys = new int[jsonKeys.size()];
for (int i = 0; i < jsonKeys.size(); i++) {
JsonElement element = jsonKeys.get(i);
keys[i] = element.getAsInt();
}
JsonArray jsonValues = json.getAsJsonObject().getAsJsonArray("values");
Object[] deserializedValues = new Object[jsonValues.size()];
for (int i = 0; i < jsonValues.size(); i++) {
JsonElement element = jsonValues.get(i);
JsonObject obj = element.getAsJsonObject();
deserializedValues[i] = context.deserialize(obj, parameterizedType);
}
SparseArray<Object> sparseArray = new SparseArray<Object>();
for (int i = 0; i < jsonValues.size(); i++) {
int key = keys[i];
Object value = deserializedValues[i];
sparseArray.put(key, value);
}
return sparseArray;
}Example 100
| Project: Tinman-master File: XapiStatementBatchJson.java View source code |
/* (non-Javadoc)
* @see com.google.gson.JsonSerializer#serialize(java.lang.Object, java.lang.reflect.Type, com.google.gson.JsonSerializationContext)
*/
@Override
public JsonElement serialize(XapiStatementBatch arg0, Type arg1, JsonSerializationContext arg2) {
JsonArray theStatementArray = new JsonArray();
if (arg0.size() == 1) {
JsonElement theStatement = arg2.serialize(arg0.getStatementAtIndex(0), XapiStatement.class);
theStatementArray.add(theStatement);
return theStatementArray;
} else {
for (XapiStatement s : arg0) {
theStatementArray.add(arg2.serialize(s, XapiStatement.class));
}
return theStatementArray;
}
}Example 101
| Project: tme-master File: JsonListWriter.java View source code |
@Override
public void writeTo(List objs, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4, MultivaluedMap<String, Object> arg5, OutputStream out) throws IOException, WebApplicationException {
JsonArray array = new JsonArray();
for (Object obj : objs) {
JsonParser parser = new JsonParser();
try {
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
StringWriter sw = new StringWriter();
JSONJAXBContext.getJSONMarshaller(marshaller).marshallToJSON(obj, sw);
array.add(parser.parse(sw.toString()));
} catch (JAXBException e) {
array.add(new JsonPrimitive(obj.toString()));
}
}
out.write(new Gson().toJson(array).getBytes());
}