下面列出了怎么用com.google.gson.JsonArray的API类实例代码及写法,或者点击链接到github查看源代码。
public static JsonArray getJsonArrayFromStorage(Context context, String name, KcaDBHelper helper) {
if (getBooleanPreferences(context, PREF_RES_USELOCAL)) {
return getJsonArrayFromAsset(context, name, helper);
} else {
ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("data", Context.MODE_PRIVATE);
File jsonFile = new File(directory, name);
JsonArray data = new JsonArray();
try {
Reader reader = new FileReader(jsonFile);
data = new JsonParser().parse(reader).getAsJsonArray();
reader.close();
} catch (IOException | IllegalStateException | JsonSyntaxException e ) {
e.printStackTrace();
setPreferences(context, PREF_DATALOAD_ERROR_FLAG, true);
if (helper != null) helper.recordErrorLog(ERROR_TYPE_DATALOAD, name, "getJsonArrayFromStorage", "0", getStringFromException(e));
data = getJsonArrayFromAsset(context, name, helper);
}
return data;
}
}
public static ModalFormRequestPacket createMain(List<String> servers) {
currentForm = MAIN;
ModalFormRequestPacket mf = new ModalFormRequestPacket();
mf.setFormId(UIForms.MAIN);
JsonObject out = UIComponents.createForm("form", "Server List");
out.addProperty("content", "");
JsonArray buttons = new JsonArray();
buttons.add(UIComponents.createButton("Connect to a Server"));
buttons.add(UIComponents.createButton("Remove a Server"));
for(int i=0;i<servers.size();i++) {
buttons.add(UIComponents.createButton(servers.get(i), "https://i.imgur.com/3BmFZRE.png", "url"));
}
buttons.add(UIComponents.createButton("The Hive", "https://forum.playhive.com/uploads/default/original/1X/0d05e3240037f7592a0f16b11b57c08eba76f19c.png", "url"));
buttons.add(UIComponents.createButton("Mineplex", "https://www.mineplex.com/assets/www-mp/img/footer/footer_smalllogo.png", "url"));
buttons.add(UIComponents.createButton("CubeCraft Games", "https://i.imgur.com/aFH1NUr.png", "url"));
buttons.add(UIComponents.createButton("Lifeboat Network", "https://lbsg.net/wp-content/uploads/2017/06/lifeboat-square.png", "url"));
buttons.add(UIComponents.createButton("Mineville City", "https://pbs.twimg.com/profile_images/1095835578451537920/0-x9qcw8.png", "url"));
out.add("buttons", buttons);
mf.setFormData(out.toString());
return mf;
}
public static List<Concept> searchConceptByName(String entity)
throws UnsupportedEncodingException, IOException, ClientProtocolException {
JSONObject queryjson = new JSONObject();
queryjson.accumulate("QUERY", entity);
System.out.println("queryjson:" + queryjson);
String vocabularyresult = getConcept(queryjson);
System.out.println("vocabularyresult length=" + vocabularyresult.length());
Gson gson = new Gson();
JsonArray ja = new JsonParser().parse(vocabularyresult).getAsJsonArray();
if (ja.size() == 0) {
System.out.println("size=" + ja.size());
return null;
}
List<Concept> list = gson.fromJson(ja, new TypeToken<List<Concept>>() {
}.getType());
return list;
}
public static void getInventoryJSON(JsonArray arr, IInventory inventory)
{
String invName = getInventoryName(inventory);
for (int i = 0; i < inventory.getSizeInventory(); i++)
{
ItemStack is = inventory.getStackInSlot(i);
if (is != null && !is.isEmpty())
{
JsonObject jobj = new JsonObject();
DrawItem di = MinecraftTypeHelper.getDrawItemFromItemStack(is);
String name = di.getType();
if (di.getColour() != null)
jobj.addProperty("colour", di.getColour().value());
if (di.getVariant() != null)
jobj.addProperty("variant", di.getVariant().getValue());
jobj.addProperty("type", name);
jobj.addProperty("index", i);
jobj.addProperty("quantity", is.getCount());
jobj.addProperty("inventory", invName);
arr.add(jobj);
}
}
}
/**
* Gets the plugin specific data.
* This method is called using Reflection.
*
* @return The plugin specific data.
*/
public JsonObject getPluginData() {
JsonObject data = new JsonObject();
String pluginName = plugin.getDescription().getName();
String pluginVersion = plugin.getDescription().getVersion();
data.addProperty("pluginName", pluginName);
data.addProperty("id", pluginId);
data.addProperty("pluginVersion", pluginVersion);
JsonArray customCharts = new JsonArray();
for (CustomChart customChart : charts) {
// Add the data of the custom charts
JsonObject chart = customChart.getRequestJsonObject(plugin.getLogger(), logFailedRequests);
if (chart == null) { // If the chart is null, we skip it
continue;
}
customCharts.add(chart);
}
data.add("customCharts", customCharts);
return data;
}
@NotNull
private static List<MolecularMatchTrialsIntervention> createInterventions(@NotNull JsonArray interventionArray) {
List<MolecularMatchTrialsIntervention> molecularMatchTrialsInterventionList = Lists.newArrayList();
ViccDatamodelChecker interventionChecker = ViccDatamodelCheckerFactory.molecularMatchTrialsInterventionChecker();
for (JsonElement interventionElement : interventionArray) {
JsonObject interventionObject = interventionElement.getAsJsonObject();
interventionChecker.check(interventionObject);
molecularMatchTrialsInterventionList.add(ImmutableMolecularMatchTrialsIntervention.builder()
.interventionName(optionalString(interventionObject, "intervention_name"))
.otherNames(optionalStringList(interventionObject, "other_name"))
.interventionType(optionalString(interventionObject, "intervention_type"))
.armGroupLabels(optionalStringList(interventionObject, "arm_group_label"))
.description(optionalString(interventionObject, "description"))
.build());
}
return molecularMatchTrialsInterventionList;
}
public static ArrayList<Object> parseArrayToBytesHierarchy(final JsonArray array) {
ArrayList<Object> arrayList = new ArrayList<>();
for (JsonElement element : array) {
if(element.isJsonObject()) {
arrayList.add(parseObject(element));
} else if(element.isJsonArray()) {
arrayList.add(parseArrayToBytesHierarchy(element.getAsJsonArray()));
} else if(element.isJsonPrimitive()) {
arrayList.add(parsePrimitiveToBytes(element));
} else if(element.isJsonNull()) {
throw new RuntimeException("null??");
} else {
throw new RuntimeException("?????");
}
}
return arrayList;
}
@Test
public void testMultiParamsParsing_02() {
Map<String, JsonRpcMethod> supportedMethods = new LinkedHashMap<>();
supportedMethods.put("foo", JsonRpcMethod.request("foo",
new TypeToken<Void>() {}.getType(),
new TypeToken<String>() {}.getType(),
new TypeToken<Integer>() {}.getType()));
MessageJsonHandler handler = new MessageJsonHandler(supportedMethods);
handler.setMethodProvider((id) -> "foo");
RequestMessage message = (RequestMessage) handler.parseMessage("{\"jsonrpc\":\"2.0\","
+ "\"id\":\"2\",\n"
+ "\"params\": [\"foo\", 2],\n"
+ "\"method\":\"bar\"\n"
+ "}");
Assert.assertTrue("" + message.getParams().getClass(), message.getParams() instanceof JsonArray);
}
public static void calculateRaigekiDamage(JsonObject damage_info) {
JsonArray damage_info_fdam = damage_info.getAsJsonArray("api_fdam");
JsonArray damage_info_edam = damage_info.getAsJsonArray("api_edam");
for (int i = 0; i < damage_info_fdam.size(); i++) {
if (isCombinedFleetInSortie() && i >= 6) {
reduce_value(true, friendCbAfterHps, i - 6, cnv(damage_info_fdam.get(i)), true);
} else {
reduce_value(true, friendAfterHps, i, cnv(damage_info_fdam.get(i)), false);
}
}
for (int i = 0; i < damage_info_edam.size(); i++) {
int value = cnv(damage_info_edam.get(i));
if (value > 0) {
if (i < 6) reduce_value(false, enemyAfterHps, i, value, false);
else reduce_value(false, enemyCbAfterHps, i - 6, value, true);
}
}
}
@Override
public List<Circuit> getApartmentCircuits(String sessionToken) {
String response = transport.execute(
SimpleRequestBuilder.buildNewJsonRequest(ClassKeys.APARTMENT).addFunction(FunctionKeys.GET_CIRCUITS)
.addParameter(ParameterKeys.TOKEN, sessionToken).buildRequestString());
JsonObject responseObj = JSONResponseHandler.toJsonObject(response);
if (JSONResponseHandler.checkResponse(responseObj)) {
responseObj = JSONResponseHandler.getResultJsonObject(responseObj);
if (responseObj.get(JSONApiResponseKeysEnum.CIRCUITS.getKey()).isJsonArray()) {
JsonArray array = responseObj.get(JSONApiResponseKeysEnum.CIRCUITS.getKey()).getAsJsonArray();
List<Circuit> circuitList = new LinkedList<Circuit>();
for (int i = 0; i < array.size(); i++) {
if (array.get(i).isJsonObject()) {
circuitList.add(new CircuitImpl(array.get(i).getAsJsonObject()));
}
}
return circuitList;
}
}
return new LinkedList<Circuit>();
}
public static void calculateFriendSupportFleetHougekiDamage(JsonObject api_data) {
JsonArray at_eflag = api_data.getAsJsonArray("api_at_eflag");
JsonArray df_list = api_data.getAsJsonArray("api_df_list");
JsonArray df_damage = api_data.getAsJsonArray("api_damage");
for (int i = 0; i < df_list.size(); i++) {
int eflag = at_eflag.get(i).getAsInt();
JsonArray target = df_list.get(i).getAsJsonArray();
JsonArray target_dmg = df_damage.get(i).getAsJsonArray();
for (int j = 0; j < target.size(); j++) {
int target_val = cnv(target.get(j));
int dmg_val = cnv(target_dmg.get(j));
boolean target_idx_cb = target.get(0).getAsInt() >= 6;
boolean target_idx_valid = target.get(0).getAsInt() != -1;
if (eflag == 0) {
if (target_idx_cb) reduce_value(false, enemyCbAfterHps, target_val - 6, dmg_val, true);
else if (target_idx_valid) reduce_value(false, enemyAfterHps, target_val, dmg_val, false);
} else { // Do not count damage for friend fleet
//if (isCombinedFleetInSortie() && target_idx_cb) reduce_value(true, friendCbAfterHps, target, -6, target_dmg, true);
//else if (target_idx_valid) reduce_value(true, friendAfterHps, target, target_dmg, false);
}
}
}
}
@Override
protected List<File> downloadArtifacts(CloseableHttpClient httpclient, JsonArray artifacts) {
final List<File> files = new ArrayList<>();
for (JsonElement ae : artifacts) {
JsonObject artifact = ae.getAsJsonObject();
if (!artifact.has("download"))
continue;
String name = jstring(artifact, "name");
String url = jstring(artifact, "download");
// Don't fail the submit if we fail to download the sab(s).
try {
File target = new File(name);
StreamsRestUtils.getFile(Executor.newInstance(httpclient), getAuthorization(), url, target);
files.add(target);
} catch (IOException e) {
TRACE.warning("Failed to download sab: " + name + " : " + e.getMessage());
}
}
return files;
}
@Test
public void testFunction() {
JsonObject args = new JsonObject();
JsonArray splitStrings = new JsonArray();
splitStrings.add("apple");
splitStrings.add("orange");
splitStrings.add("banana");
args.add("result", splitStrings);
JsonObject response = FunctionApp.main(args);
assertNotNull(response);
JsonArray results = response.getAsJsonArray("result");
assertNotNull(results);
assertEquals(3, results.size());
List<String> actuals = new ArrayList<>();
results.forEach(j -> actuals.add(j.getAsString()));
assertTrue(actuals.contains("APPLE"));
assertTrue(actuals.contains("ORANGE"));
assertTrue(actuals.contains("BANANA"));
}
@Override
public List<AllocatedSceneRange> deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
final List<AllocatedSceneRange> sceneRanges = new ArrayList<>();
try {
final JsonArray jsonObject = json.getAsJsonArray();
for (int i = 0; i < jsonObject.size(); i++) {
final JsonObject unicastRangeJson = jsonObject.get(i).getAsJsonObject();
final int firstScene = Integer.parseInt(unicastRangeJson.get("firstScene").getAsString(), 16);
final int lastScene = Integer.parseInt(unicastRangeJson.get("lastScene").getAsString(), 16);
sceneRanges.add(new AllocatedSceneRange(firstScene, lastScene));
}
} catch (Exception ex) {
Log.e(TAG, "Error while de-serializing allocated scene range: " + ex.getMessage());
}
return sceneRanges;
}
@NotNull
public static Case readCase(@NotNull String file) {
final String raw;
try {
raw = IOUtils.resourceToString(file, StandardCharsets.UTF_8, TestUtils.class.getClassLoader());
} catch (Throwable t) {
throw new RuntimeException(t);
}
if (raw == null
|| raw.length() == 0) {
throw new RuntimeException("Test file has no contents, file: " + file);
}
final String[] split = raw.split(DELIMITER);
if (split.length < 2) {
throw new RuntimeException("Test file seems to have wrong delimiter, file: " + file);
}
final String input = split[0].trim();
final JsonArray simplifiedOutput = GSON.fromJson(split[1].trim(), JsonArray.class);
final String description = split[2].trim();
return new Case(input, simplifiedOutput, description);
}
public static ArrayList<Product> parseJsonArray(JsonArray jsonArray) {
ArrayList<Product> products = new ArrayList<>(jsonArray.size());
Gson gson = new Gson();
for (int i=0 ; i<jsonArray.size() ; i++) {
JsonObject jsonObject = jsonArray.get(i).getAsJsonObject();
Product product = gson.fromJson(jsonObject, Product.class);
// temp hack for build
for (int j=0 ; j<product.getImages().length ; j++) {
product.getImages()[j].setPath(product.getImages()[j].getPath().replace("-catalogmobile", ""));
}
products.add(product);
}
return products;
}
/**
* Returns serialized json element containing the groups
*
* @param groups Group list
* @return JsonElement
*/
private JsonElement serializeGroups(@NonNull final List<Group> groups) {
JsonArray groupsArray = new JsonArray();
for (Group group : groups) {
JsonObject groupObj = new JsonObject();
groupObj.addProperty("name", group.getName());
if (group.getAddressLabel() == null) {
groupObj.addProperty("address", MeshAddress.formatAddress(group.getAddress(), false));
} else {
groupObj.addProperty("address", MeshParserUtils.uuidToHex(group.getAddressLabel()));
}
groupObj.addProperty("parentAddress", MeshAddress.formatAddress(group.getParentAddress(), false));
groupsArray.add(groupObj);
}
return groupsArray;
}
private JsonArray getDegreeFinalizationInfoEntries() {
if (getDocumentRequest().getDetailed()) {
JsonArray result = new JsonArray();
final SortedSet<ICurriculumEntry> entries =
new TreeSet<ICurriculumEntry>(ICurriculumEntry.COMPARATOR_BY_EXECUTION_PERIOD_AND_NAME_AND_ID);
entries.addAll(getDocumentRequest().getEntriesToReport());
final Map<Unit, String> academicUnitIdentifiers = new HashMap<Unit, String>();
reportEntries(result, entries, academicUnitIdentifiers);
if (getDocumentRequest().isToShowCredits()) {
getRemainingCreditsInfoValue(getDocumentRequest().getCurriculum()).ifPresent(value ->{
getPayload().addProperty("remainingCreditsInfoValue", value);
});
}
if (!academicUnitIdentifiers.isEmpty()) {
getPayload().add("academicUnitInfoValues", getAcademicUnitInfoValues(academicUnitIdentifiers, getDocumentRequest().getMobilityProgram()));
}
return result;
}
return null;
}
public static JsonArray getJsonArrayFromStorage(Context context, String name, KcaDBHelper helper) {
if (getBooleanPreferences(context, PREF_RES_USELOCAL)) {
return getJsonArrayFromAsset(context, name, helper);
} else {
ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("data", Context.MODE_PRIVATE);
File jsonFile = new File(directory, name);
JsonArray data = new JsonArray();
try {
Reader reader = new FileReader(jsonFile);
data = new JsonParser().parse(reader).getAsJsonArray();
reader.close();
} catch (IOException | IllegalStateException | JsonSyntaxException e ) {
e.printStackTrace();
setPreferences(context, PREF_DATALOAD_ERROR_FLAG, true);
if (helper != null) helper.recordErrorLog(ERROR_TYPE_DATALOAD, name, "getJsonArrayFromStorage", "0", getStringFromException(e));
data = getJsonArrayFromAsset(context, name, helper);
}
return data;
}
}
@Test
public void testRawMultiParamsParsing_02() {
Map<String, JsonRpcMethod> supportedMethods = new LinkedHashMap<>();
supportedMethods.put("foo", JsonRpcMethod.request("foo",
new TypeToken<Void>() {}.getType(),
new TypeToken<String>() {}.getType(),
new TypeToken<Integer>() {}.getType()));
DebugMessageJsonHandler handler = new DebugMessageJsonHandler(supportedMethods);
handler.setMethodProvider((id) -> "foo");
RequestMessage message = (RequestMessage) handler.parseMessage("{"
+ "\"seq\":2,\n"
+ "\"type\":\"request\",\n"
+ "\"command\":\"bar\",\n"
+ "\"arguments\": [\"foo\", 2]\n"
+ "}");
Assert.assertTrue("" + message.getParams().getClass(), message.getParams() instanceof JsonArray);
}
public String getConditionStatus(JsonArray deckPortData, int deckid) {
String getConditionInfo = "";
List<String> conditionList = new ArrayList<String>();
JsonArray deckShipIdList = (JsonArray) ((JsonObject) deckPortData.get(deckid)).get("api_ship");
for (int i = 0; i < deckShipIdList.size(); i++) {
int shipId = deckShipIdList.get(i).getAsInt();
if (shipId != -1) {
JsonObject shipData = getUserShipDataById(shipId, "cond");
int shipCondition = shipData.get("cond").getAsInt();
conditionList.add(String.valueOf(shipCondition));
}
}
if(conditionList.size() == 0) {
getConditionInfo = "";
} else {
getConditionInfo = joinStr(conditionList, "/");
}
return getConditionInfo;
}
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
JsonArray categoryValues = new JsonArray();
categoryValues.add(new JsonPrimitive(entry.getValue()));
values.add(entry.getKey(), categoryValues);
}
data.add("values", values);
return data;
}
private JsonObject createGetMetadataResponse(APIGetMetadata response) {
JsonObject jResponse = new JsonObject();
if (response.getSuccess()) {
ItemMetadata metadata = response.getItemMetadata();
jResponse = parseObjectMetadataForAPI(metadata);
if (metadata.getChildren() != null) {
JsonArray contents = new JsonArray();
for (ItemMetadata entry : metadata.getChildren()) {
JsonObject entryJson = parseObjectMetadataForAPI(entry);
contents.add(entryJson);
}
jResponse.add("contents", contents);
}
} else {
jResponse.addProperty("error", response.getErrorCode());
jResponse.addProperty("description", response.getDescription());
}
return jResponse;
}
private List<String> deserializeLocationsFromJsonElement(final JsonElement jsonElement) {
final JsonArray jsonLocations = jsonElement.getAsJsonArray();
if (jsonLocations == null) {
return null;
}
// Parse each location:
final List<String> locations = new ArrayList<>();
for (final JsonElement jsonLocation : jsonLocations) {
final JsonObject asObject = jsonLocation.getAsJsonObject();
final String url = JsonUtils.getString(asObject, "image/jpeg");
if (url != null) {
locations.add(url);
}
}
return locations;
}
private List<NodeKey> deserializeAddedIndexes(final JsonArray jsonNetKeyIndexes) {
List<NodeKey> addedKeys = new ArrayList<>();
for (int i = 0; i < jsonNetKeyIndexes.size(); i++) {
final JsonObject jsonAddedKeys = jsonNetKeyIndexes.get(i).getAsJsonObject();
final int index = jsonAddedKeys.get("index").getAsInt();
boolean updated = false;
if (jsonAddedKeys.has("updated")) {
updated = jsonAddedKeys.get("updated").getAsBoolean();
}
addedKeys.add(new NodeKey(index, updated));
}
return addedKeys;
}
private Boolean equalFilters(JsonArray fs1, JsonArray fs2) {
//compare element size
if(fs1.size() == fs2.size()){
//Check if every filter is in the second list of filters
return Streams.stream(fs1.iterator()).allMatch( f1 ->
Streams.stream(fs2.iterator())
.anyMatch( f -> equalFilters(f.getAsJsonObject(),f1.getAsJsonObject()))
);
}
return false;
}
@Nullable
static JsonArray convertArray(Float[] value) {
if (value != null) {
JsonArray jsonArray = new JsonArray();
for (Float element : value) {
jsonArray.add(element);
}
return jsonArray;
} else {
return null;
}
}
private void modifyUserListChildren(JsonArray children) {
for(int i = 0 ; i < children.size() ; i++){
JsonElement child = children.get(i);
if(child.isJsonObject()){
JsonObject obj = new JsonObject();
obj.add(KIND, new JsonPrimitive(RedditType.User.toString()));
obj.add(DATA, child);
children.set(i, obj);
}
}
}
private static FireworkEffect getFireworkEffect(JsonObject json) {
FireworkEffect.Builder builder = FireworkEffect.builder();
//colors
JsonArray colors = json.getAsJsonArray("colors");
for (int j = 0; j < colors.size() - 1; j++) {
builder.withColor(getColor(colors.get(j).getAsJsonObject()));
}
//fade colors
JsonArray fadeColors = json.getAsJsonArray("fade-colors");
for (int j = 0; j < fadeColors.size() - 1; j++) {
builder.withFade(getColor(colors.get(j).getAsJsonObject()));
}
//hasFlicker
if (json.get("flicker").getAsBoolean())
builder.withFlicker();
//trail
if (json.get("trail").getAsBoolean())
builder.withTrail();
//type
builder.with(FireworkEffect.Type.valueOf(json.get("type").getAsString()));
return builder.build();
}
@Test
public void testConverterWithNestJson() throws Exception {
Gson gson = new Gson();
jsonSchema = gson.fromJson(new InputStreamReader(
this.getClass().getResourceAsStream("/converter/nested_schema.json")),
JsonArray.class);
jsonRecord = gson.fromJson(new InputStreamReader(
this.getClass().getResourceAsStream("/converter/nested_json.json")),
JsonObject.class);
WorkUnit workUnit = new WorkUnit(new SourceState(),
new Extract(new SourceState(), Extract.TableType.SNAPSHOT_ONLY, "namespace", "dummy_table"));
state = new WorkUnitState(workUnit);
state.setProp(ConfigurationKeys.CONVERTER_AVRO_TIME_FORMAT, "HH:mm:ss");
state.setProp(ConfigurationKeys.CONVERTER_AVRO_DATE_TIMEZONE, "PST");
JsonIntermediateToAvroConverter converter = new JsonIntermediateToAvroConverter();
Schema avroSchema = converter.convertSchema(jsonSchema, state);
GenericRecord record = converter.convertRecord(avroSchema,
jsonRecord.getAsJsonObject(), state).iterator().next();
Assert.assertEquals(jsonRecord.getAsJsonObject().get("metaData").getAsJsonObject(),
gson.fromJson(record.get("metaData").toString(), JsonObject.class));
Assert.assertEquals(jsonRecord.getAsJsonObject().get("context").getAsJsonArray(),
gson.fromJson(record.get("context").toString(), JsonArray.class));
Assert.assertEquals(jsonRecord.getAsJsonObject().get("metaData").getAsJsonObject().get("id").getAsString(),
((GenericRecord)(record.get("metaData"))).get("id").toString());
}