List of usage examples for com.google.gson JsonArray iterator
public Iterator<JsonElement> iterator()
From source file:org.apache.tika.metadata.serialization.JsonMetadataDeserializer.java
License:Apache License
/** * Deserializes a json object (equivalent to: Map<String, String[]>) * into a Metadata object.//from w w w .j a va 2s. c o m * * @param element to serialize * @param type (ignored) * @param context (ignored) * @return Metadata * @throws JsonParseException if element is not able to be parsed */ @Override public Metadata deserialize(JsonElement element, Type type, JsonDeserializationContext context) throws JsonParseException { final JsonObject obj = element.getAsJsonObject(); Metadata m = new Metadata(); for (Map.Entry<String, JsonElement> entry : obj.entrySet()) { String key = entry.getKey(); JsonElement v = entry.getValue(); if (v.isJsonPrimitive()) { m.set(key, v.getAsString()); } else if (v.isJsonArray()) { JsonArray vArr = v.getAsJsonArray(); Iterator<JsonElement> itr = vArr.iterator(); while (itr.hasNext()) { JsonElement valueItem = itr.next(); m.add(key, valueItem.getAsString()); } } } return m; }
From source file:org.bimserver.collada.OpenGLTransmissionFormatSerializer.java
License:Open Source License
private JsonElement selectivelyJoinTwoJSONElements(JsonElement baseElement, JsonElement otherElement, String suffix) {//from w w w. j a v a 2 s . c o m JsonObject base = baseElement.getAsJsonObject(); JsonObject other = otherElement.getAsJsonObject(); // if (other.has("accessors")) { JsonElement accesssorsElement = getOrCreateJSONElement(base, "accessors"); JsonObject accesssorsObject = accesssorsElement.getAsJsonObject(); JsonObject joining = other.get("accessors").getAsJsonObject(); // Entry set yields key like: accessor_16. for (Map.Entry<String, JsonElement> entry : joining.entrySet()) { // Get: "accessor_16", { "bufferView": "bufferView_22", ... } String propertyName = entry.getKey(); JsonElement joiningElement = entry.getValue(); // Cast to dictionary object. JsonObject joiningObject = joiningElement.getAsJsonObject(); // Convert: accessor_16 to accessor_16_suffix. String safePropertyName = String.format("%s_%s", propertyName, suffix); // Get the element of the bufferView, which is in form "bufferView_22". JsonElement bufferViewElement = joiningObject.get("bufferView"); String bufferViewName = bufferViewElement.getAsString(); // Create a new bufferView name: bufferView_22_suffix. String safeBufferViewName = String.format("%s_%s", bufferViewName, suffix); // Remove the existing path element. joiningObject.remove("bufferView"); // Add the new one, containing the safety name: bufferView_22_suffix. joiningObject.addProperty("bufferView", safeBufferViewName); // "accesor_16_suffix": { "bufferView": "bufferView_22_suffix", ... } accesssorsObject.add(safePropertyName, joiningElement); } } if (other.has("bufferViews")) { JsonElement bufferViewsElement = getOrCreateJSONElement(base, "bufferViews"); JsonObject bufferViewsObject = bufferViewsElement.getAsJsonObject(); JsonObject joining = other.get("bufferViews").getAsJsonObject(); // Entry set yields key like: bufferView_22 for (Map.Entry<String, JsonElement> entry : joining.entrySet()) { // Get: "bufferView_22", { "buffer": "P1", ... } String propertyName = entry.getKey(); JsonElement joiningElement = entry.getValue(); // Cast to dictionary. JsonObject joiningObject = joiningElement.getAsJsonObject(); // Only include buffer view objects that aren't empty (because empty ones aren't referenced by collada2gltf, but collada2gltf erroneously includes them anyway during Open3DGC compression). if (joiningObject.get("byteLength").getAsInt() > 0) { // Convert: bufferView_22 to bufferView_22_suffix. String safePropertyName = String.format("%s_%s", propertyName, suffix); // Get the element of the buffer; value is a key to look up data beneath the "buffers" dictionary. JsonElement bufferElement = joiningObject.get("buffer"); // Get the buffer name: compression. String bufferName = bufferElement.getAsString(); // Convert: compression to compression_suffix. String safeBufferName = (bufferName.equalsIgnoreCase("compression")) ? String.format("%s_%s", bufferName, suffix) : bufferName; // Remove the existing buffer element. joiningObject.remove("buffer"); // Add the new one, containing the safety name(s): bufferView_22_suffix and P1_suffix. joiningObject.addProperty("buffer", safeBufferName); // "bufferView_22_suffix": { "buffer": "P1_suffix", ... } bufferViewsObject.add(safePropertyName, joiningElement); } } } if (other.has("buffers")) { JsonElement buffersElement = getOrCreateJSONElement(base, "buffers"); JsonObject buffersObject = buffersElement.getAsJsonObject(); JsonObject joining = other.get("buffers").getAsJsonObject(); // Entry set yields key like: P1 (name of converted file) or "compression" (if using Open3DGC compression). for (Map.Entry<String, JsonElement> entry : joining.entrySet()) { // Get: "P1", { "path": "P1.bin", ... } String propertyName = entry.getKey(); JsonElement joiningElement = entry.getValue(); // Cast to dictionary object. JsonObject joiningObject = joiningElement.getAsJsonObject(); // Only include buffer view objects that aren't empty (because empty ones aren't referenced by collada2gltf, but collada2gltf erroneously includes them anyway during Open3DGC compression). if (joiningObject.get("byteLength").getAsInt() > 0) { if (propertyName.equalsIgnoreCase("compression")) { // Convert: compression to compression_suffix. String safePropertyName = String.format("%s_%s", propertyName, suffix); // Get the element of the path to file, which is in form "P1.bin" or "compression.bin". JsonElement pathElement = joiningObject.get("path"); String pathName = pathElement.getAsString(); // Extract the file without the extension: P1. String basePathName = FilenameUtils.removeExtension(pathName); // Extract the extension: bin. String fileExtension = FilenameUtils.getExtension(pathName); // Create a new file name: P1_suffix.bin. String safePathName = String.format("%s_%s.%s", basePathName, suffix, fileExtension); // Remove the existing path element. joiningObject.remove("path"); // Add the new one, containing the safety name: P1_suffix.bin. joiningObject.addProperty("path", safePathName); // "P1_suffix": { "path": "P1_suffix.bin", ... } buffersObject.add(safePropertyName, joiningElement); } else buffersObject.add(propertyName, joiningElement); } } } // Prepare a place to store technique rewrites to be used only in the material definitions. List<SimpleEntry<String, String>> techniqueReplacementTable = new ArrayList<SimpleEntry<String, String>>(); // List<SimpleEntry<String, String>> programReplacementTable = new ArrayList<SimpleEntry<String, String>>(); // Techniques must happen before materials. if (other.has("techniques")) { JsonElement techniquesElement = getOrCreateJSONElement(base, "techniques"); JsonObject techniquesObject = techniquesElement.getAsJsonObject(); JsonObject joining = other.get("techniques").getAsJsonObject(); // Entry set yields key like: technique0. for (Map.Entry<String, JsonElement> entry : joining.entrySet()) { // Get: "technique0", { ... } String propertyName = entry.getKey(); JsonElement joiningElement = entry.getValue(); JsonObject techniqueObject = joiningElement.getAsJsonObject(); // Look for existing technique/program. String equivalentTechnique = nameOfEquivalentTechniqueInBaseObject(base, other, propertyName); if (equivalentTechnique != null) techniqueReplacementTable .add(new SimpleEntry<String, String>(propertyName, equivalentTechnique)); else { // If not equivalent, count number of techniques; return that count + 1 as safeTechniqueNumber. int safeTechniqueNumber = nextSafeTechniqueNumber(techniquesObject); // Then, write a replacement technique object with key: "technique%d" where %d is safeTechniqueNumber. String safeTechniqueName = String.format("technique%d", safeTechniqueNumber); techniqueReplacementTable.add(new SimpleEntry<String, String>(propertyName, safeTechniqueName)); // Then, count number of programs; return that count + 1 as firstSafeProgramNumber. JsonElement baseProgramsElement = getOrCreateJSONElement(base, "programs"); JsonObject baseProgramsObject = baseProgramsElement.getAsJsonObject(); int firstSafeProgramNumber = nextSafeProgramNumber(baseProgramsObject); // Then, rewrite the object's "passes" -> pass -> "instanceProgram" -> "program" to be "program_%d" where %d is firstSafeProgramNumber. JsonObject passesObject = techniqueObject.get("passes").getAsJsonObject(); JsonObject programsObject = other.get("programs").getAsJsonObject(); JsonObject shadersObject = other.get("shaders").getAsJsonObject(); JsonObject baseShadersObject = getOrCreateJSONElement(base, "shaders").getAsJsonObject(); for (Entry<String, JsonElement> passEntry : passesObject.entrySet()) { JsonObject passObject = passEntry.getValue().getAsJsonObject(); JsonObject instanceProgramObject = passObject.get("instanceProgram").getAsJsonObject(); // Get existing program name. String programNameToRewrite = instanceProgramObject.get("program").getAsString(); // SimpleEntry<String, String> equivalentProgramReplacementEntry = getEntryByKey( programNameToRewrite, programReplacementTable); String safeProgramName; if (equivalentProgramReplacementEntry != null) { // If the program can request an equivalent program, just rewrite the name in the pass. safeProgramName = equivalentProgramReplacementEntry.getValue(); } else { // If the program cannot request an equivalent program, rewrite the name in the pass // Get a safe name for the program. safeProgramName = String.format("program_%d", firstSafeProgramNumber); firstSafeProgramNumber++; // Mark the existing program name to be rewritten as the safe program name. programReplacementTable .add(new SimpleEntry<String, String>(programNameToRewrite, safeProgramName)); // Get the existing program object. JsonObject programObject = programsObject.get(programNameToRewrite).getAsJsonObject(); // Add applicable shaders to the base object. for (String shaderCategory : Arrays.asList("fragmentShader", "vertexShader", "geometryShader", "tessellationShader", "computeShader")) { if (programObject.has(shaderCategory)) { String shaderName = programObject.get(shaderCategory).getAsString(); JsonElement shaderElement = shadersObject.get(shaderName); // TODO: Optionally, rename shader files. // Add shaders to base object. baseShadersObject.add(shaderName, shaderElement); } } // Add the program to the base object under the safe program name. baseProgramsObject.add(safeProgramName, programObject); } // Update the program in the pass's "instanceProgram" -> "program" from: program_0 to program_safeProgramNumber instanceProgramObject.remove("program"); instanceProgramObject.addProperty("program", safeProgramName); } // Add technique to base object. techniquesObject.add(safeTechniqueName, joiningElement); } } } if (other.has("materials")) { JsonElement materialsElement = getOrCreateJSONElement(base, "materials"); JsonObject materialsObject = materialsElement.getAsJsonObject(); JsonObject joining = other.get("materials").getAsJsonObject(); // Entry set yields key like: IfcSlab-fx. for (Map.Entry<String, JsonElement> entry : joining.entrySet()) { // Get: "IfcSlab-fx", { ... } String propertyName = entry.getKey(); JsonElement joiningElement = entry.getValue(); if (!materialsObject.has(propertyName)) { JsonObject otherSpecificMaterialObject = joiningElement.getAsJsonObject(); JsonObject otherInstanceTechniqueObject = otherSpecificMaterialObject.get("instanceTechnique") .getAsJsonObject(); String techniqueRequest = otherInstanceTechniqueObject.get("technique").getAsString(); // Check if there's an existing replacement entry to translate requests for technique0 to techniqueX. SimpleEntry<String, String> replacementEntry = getEntryByKey(techniqueRequest, techniqueReplacementTable); if (replacementEntry != null) { String newTechnique = replacementEntry.getValue(); otherInstanceTechniqueObject.remove("technique"); otherInstanceTechniqueObject.addProperty("technique", newTechnique); } // Otherwise, see if there's an one available in the base object. else { String newTechnique = nameOfEquivalentTechniqueInBaseObject(base, other, techniqueRequest); if (newTechnique != null) { otherInstanceTechniqueObject.remove("technique"); otherInstanceTechniqueObject.addProperty("technique", newTechnique); } } materialsObject.add(propertyName, joiningElement); } } } if (other.has("meshes")) { JsonElement meshesElement = getOrCreateJSONElement(base, "meshes"); JsonObject meshesObject = meshesElement.getAsJsonObject(); JsonObject joining = other.get("meshes").getAsJsonObject(); // Entry set yields key like: "geom-131696". for (Map.Entry<String, JsonElement> entry : joining.entrySet()) { // Get: "geom-131696", { "primitives": [{ "attributes": { "NORMAL": "accessor_20", ... }, "indices": "accesor_16", ... }, ], ... } String propertyName = entry.getKey(); JsonElement joiningElement = entry.getValue(); if (!meshesObject.has(propertyName)) { // Cast to dictionary object. JsonObject joiningObject = joiningElement.getAsJsonObject(); // Get primitives array element. JsonElement primitivesArrayElement = joiningObject.get("primitives"); JsonArray primitivesArray = primitivesArrayElement.getAsJsonArray(); Iterator<JsonElement> iterator = primitivesArray.iterator(); while (iterator.hasNext()) { JsonElement dictionaryElement = iterator.next(); JsonObject dictionaryObject = dictionaryElement.getAsJsonObject(); // Get "attributes" sub-section. JsonElement attributesElement = dictionaryObject.get("attributes"); JsonObject attributesObject = attributesElement.getAsJsonObject(); JsonObject newAttributesObject = new JsonObject(); // Yields keys like: "NORMAL", "POSITION", etc. for (Entry<String, JsonElement> thisEntry : attributesObject.entrySet()) { String thisKey = thisEntry.getKey(); JsonElement thisElement = thisEntry.getValue(); String accessorName = thisElement.getAsString(); String safeAccessorName = String.format("%s_%s", accessorName, suffix); newAttributesObject.addProperty(thisKey, safeAccessorName); } dictionaryObject.remove("attributes"); dictionaryObject.add("attributes", newAttributesObject); // Get "indices" entry. JsonElement indicesElement = dictionaryObject.get("indices"); String indicesAccessorName = indicesElement.getAsString(); String safeIndicesAccessorName = String.format("%s_%s", indicesAccessorName, suffix); dictionaryObject.remove("indices"); dictionaryObject.addProperty("indices", safeIndicesAccessorName); } if (joiningObject.has("extensions")) { // Get extensions dictionary. Iterate keys. JsonObject extensionsObject = joiningObject.get("extensions").getAsJsonObject(); // Yields things like: Open3DGC-compression for (Entry<String, JsonElement> extension : extensionsObject.entrySet()) { JsonElement payload = extension.getValue(); if (payload instanceof JsonObject) { JsonObject payloadObject = payload.getAsJsonObject(); // Get "compressedData"? for (Entry<String, JsonElement> payloadElement : payloadObject.entrySet()) { JsonElement itemElement = payloadElement.getValue(); // if (itemElement instanceof JsonObject) { // JsonObject itemObject = itemElement.getAsJsonObject(); if (itemObject.has("bufferView")) { String bufferViewName = itemObject.get("bufferView").getAsString(); String safeBufferViewName = String.format("%s_%s", bufferViewName, suffix); itemObject.remove("bufferView"); itemObject.addProperty("bufferView", safeBufferViewName); } } } } } } // "P1_suffix": { "path": "P1_suffix.bin", ... } meshesObject.add(propertyName, joiningElement); } } } if (other.has("nodes")) { JsonElement nodesElement = getOrCreateJSONElement(base, "nodes"); JsonObject nodesObject = nodesElement.getAsJsonObject(); JsonObject joining = other.get("nodes").getAsJsonObject(); // Entry set yields key like: node-131696. for (Map.Entry<String, JsonElement> entry : joining.entrySet()) { // Get: "node-131696", { ... } String propertyName = entry.getKey(); JsonElement joiningElement = entry.getValue(); if (!nodesObject.has(propertyName)) nodesObject.add(propertyName, joiningElement); } } if (other.has("scenes")) { JsonElement scenesElement = getOrCreateJSONElement(base, "scenes"); JsonObject scenesObject = scenesElement.getAsJsonObject(); JsonObject joining = other.get("scenes").getAsJsonObject(); // Entry set yields key like: defaultScene. for (Map.Entry<String, JsonElement> entry : joining.entrySet()) { // Get: "defaultScene", { "nodes": [ "node-131696", ... ], } String propertyName = entry.getKey(); JsonElement joiningElement = entry.getValue(); // Scene key not found in the base, so add the whole thing. if (!scenesObject.has(propertyName)) scenesObject.add(propertyName, joiningElement); // Scene key is found in the base, so append the values. else { // Get the base propertyName (dictionary) -> "nodes" array. JsonElement baseScene = scenesObject.get(propertyName); JsonObject baseSceneObject = baseScene.getAsJsonObject(); JsonElement baseNodesElement = baseSceneObject.get("nodes"); JsonArray baseNodesArray = baseNodesElement.getAsJsonArray(); // Get the joining propertyName (dictionary) -> "nodes" array. JsonObject joiningObject = joiningElement.getAsJsonObject(); JsonElement nodesElement = joiningObject.get("nodes"); JsonArray nodesArray = nodesElement.getAsJsonArray(); // Add the values. baseNodesArray.addAll(nodesArray); } } } return baseElement; }
From source file:org.blockartistry.DynSurround.client.footsteps.parsers.AcousticsJsonReader.java
License:MIT License
private IAcoustic solveAcousticsCompound(final JsonObject unsolved) throws JsonParseException { IAcoustic ret = null;/*from w ww.j av a 2 s . c o m*/ if (!unsolved.has("type") || unsolved.get("type").getAsString().equals("basic")) { final BasicAcoustic a = new BasicAcoustic(); prepareDefaults(a); setupClassics(a, unsolved); ret = a; } else { final String type = unsolved.get("type").getAsString(); if (type.equals("simultaneous")) { final List<IAcoustic> acoustics = new ArrayList<IAcoustic>(); final JsonArray sim = unsolved.getAsJsonArray("array"); final Iterator<JsonElement> iter = sim.iterator(); while (iter.hasNext()) { final JsonElement subElement = iter.next(); acoustics.add(solveAcoustic(subElement)); } final SimultaneousAcoustic a = new SimultaneousAcoustic(acoustics); ret = a; } else if (type.equals("delayed")) { final DelayedAcoustic a = new DelayedAcoustic(); prepareDefaults(a); setupClassics(a, unsolved); if (unsolved.has("delay")) { a.setDelayMin(unsolved.get("delay").getAsInt()); a.setDelayMax(unsolved.get("delay").getAsInt()); } else { a.setDelayMin(unsolved.get("delay_min").getAsInt()); a.setDelayMax(unsolved.get("delay_max").getAsInt()); } ret = a; } else if (type.equals("probability")) { final List<Integer> weights = new ArrayList<Integer>(); final List<IAcoustic> acoustics = new ArrayList<IAcoustic>(); final JsonArray sim = unsolved.getAsJsonArray("array"); final Iterator<JsonElement> iter = sim.iterator(); while (iter.hasNext()) { JsonElement subElement = iter.next(); weights.add(subElement.getAsInt()); if (!iter.hasNext()) throw new JsonParseException("Probability has odd number of children!"); subElement = iter.next(); acoustics.add(solveAcoustic(subElement)); } final ProbabilityWeightsAcoustic a = new ProbabilityWeightsAcoustic(acoustics, weights); ret = a; } } return ret; }
From source file:org.broad.igv.ga4gh.Ga4ghAlignment.java
License:Open Source License
private byte[] generateBaseQualities(JsonArray alignedQuality) { byte[] baseQualities = new byte[alignedQuality.size()]; Iterator<JsonElement> iter = alignedQuality.iterator(); int i = 0;//from w ww.j a v a2 s.c o m while (iter.hasNext()) { baseQualities[i++] = iter.next().getAsByte(); } return baseQualities; }
From source file:org.broad.igv.ga4gh.Ga4ghAlignment.java
License:Open Source License
private String generateCigarString(JsonArray cigar) { StringBuffer cigarStr = new StringBuffer(); Iterator<JsonElement> iter = cigar.iterator(); while (iter.hasNext()) { JsonObject op = iter.next().getAsJsonObject(); cigarStr.append(op.getAsJsonPrimitive("operationLength").getAsString()); cigarStr.append(CigarMap.get(op.getAsJsonPrimitive("operation").getAsString())); }/*from ww w .j ava 2 s . c om*/ return cigarStr.toString(); }
From source file:org.broad.igv.ga4gh.Ga4ghAPIHelper.java
License:Open Source License
public static List<Alignment> searchReads(Ga4ghProvider provider, String readGroupSetId, String chr, int start, int end, boolean handleError) throws IOException { List<Alignment> alignments = new ArrayList<Alignment>(10000); int maxPages = 10000; JsonPrimitive pageToken = null;//from w ww . ja v a 2 s . c o m StringBuffer result = new StringBuffer(); int counter = 0; while (maxPages-- > 0) { String contentToPost = "{" + "\"readGroupSetIds\": [\"" + readGroupSetId + "\"]" + ", \"referenceName\": \"" + chr + "\"" + ", \"start\": \"" + start + "\"" + ", \"end\": \"" + end + "\"" + ", \"pageSize\": \"10000\"" + (pageToken == null ? "" : ", \"pageToken\": " + pageToken) + "}"; String readString = doPost(provider, "/reads/search", contentToPost, "", handleError); if (readString == null) { return null; } JsonParser parser = new JsonParser(); JsonObject obj = parser.parse(readString).getAsJsonObject(); JsonArray reads = obj.getAsJsonArray("alignments"); Iterator<JsonElement> iter = reads.iterator(); while (iter.hasNext()) { JsonElement next = iter.next(); Ga4ghAlignment alignment = new Ga4ghAlignment(next.getAsJsonObject()); alignments.add(alignment); } pageToken = obj.getAsJsonPrimitive("nextPageToken"); if (pageToken == null || pageToken.getAsString().equals("")) break; } return alignments; }
From source file:org.dartlang.analysis.server.protocol.ClosingLabel.java
License:Open Source License
public static List<ClosingLabel> fromJsonArray(JsonArray jsonArray) { if (jsonArray == null) { return EMPTY_LIST; }/*from www. j av a 2 s .c o m*/ ArrayList<ClosingLabel> list = new ArrayList<ClosingLabel>(jsonArray.size()); Iterator<JsonElement> iterator = jsonArray.iterator(); while (iterator.hasNext()) { list.add(fromJson(iterator.next().getAsJsonObject())); } return list; }
From source file:org.dartlang.analysis.server.protocol.ContextData.java
License:Open Source License
public static List<ContextData> fromJsonArray(JsonArray jsonArray) { if (jsonArray == null) { return EMPTY_LIST; }/*from ww w . java 2 s . c o m*/ ArrayList<ContextData> list = new ArrayList<ContextData>(jsonArray.size()); Iterator<JsonElement> iterator = jsonArray.iterator(); while (iterator.hasNext()) { list.add(fromJson(iterator.next().getAsJsonObject())); } return list; }
From source file:org.dartlang.analysis.server.protocol.FlutterOutline.java
License:Open Source License
public static List<FlutterOutline> fromJsonArray(JsonArray jsonArray) { if (jsonArray == null) { return EMPTY_LIST; }//from w w w . j av a 2s . c o m ArrayList<FlutterOutline> list = new ArrayList<FlutterOutline>(jsonArray.size()); Iterator<JsonElement> iterator = jsonArray.iterator(); while (iterator.hasNext()) { list.add(fromJson(iterator.next().getAsJsonObject())); } return list; }
From source file:org.dartlang.analysis.server.protocol.FlutterOutlineAttribute.java
License:Open Source License
public static List<FlutterOutlineAttribute> fromJsonArray(JsonArray jsonArray) { if (jsonArray == null) { return EMPTY_LIST; }/*from w w w. j av a 2 s . c o m*/ ArrayList<FlutterOutlineAttribute> list = new ArrayList<>(jsonArray.size()); Iterator<JsonElement> iterator = jsonArray.iterator(); //noinspection WhileLoopReplaceableByForEach while (iterator.hasNext()) { list.add(fromJson(iterator.next().getAsJsonObject())); } return list; }