Java Code Examples for com.google.gson.JsonElement#getAsJsonArray()

The following examples show how to use com.google.gson.JsonElement#getAsJsonArray() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JsonParserSubjects.java    From android-galaxyzoo with GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example 2
Source File: PropsTableViewTest.java    From karyon with Apache License 2.0 6 votes vote down vote up
@Test
public void propValueSearchTest() {
    final PropsTableView ptv = new PropsTableView();
    ptv.setColumnSearchTerm(PropsTableView.VALUE, PROP_VALUE_SEARCH_STR);

    final JsonArray data = ptv.getData();
    assertTrue(data != null);
    int totalElms = data.size();
    assertTrue(totalElms > 0);

    for (int i = 0; i < totalElms; i++) {
        final JsonElement propElm = data.get(i);
        final JsonArray propKVArray = propElm.getAsJsonArray();
        assertTrue(propKVArray.size() == 2);
        final String propValue = propKVArray.get(1).getAsString().toLowerCase();
        assertTrue("Property " + propValue + " does not contain " + PROP_VALUE_SEARCH_STR, (propValue.contains(PROP_VALUE_SEARCH_STR)));
    }
}
 
Example 3
Source File: VectorColumnFiller.java    From secor with Apache License 2.0 6 votes vote down vote up
public void convert(JsonElement value, ColumnVector vect, int row) {
    if (value == null || value.isJsonNull()) {
        vect.noNulls = false;
        vect.isNull[row] = true;
    } else {
        ListColumnVector vector = (ListColumnVector) vect;
        JsonArray obj = value.getAsJsonArray();
        vector.lengths[row] = obj.size();
        vector.offsets[row] = vector.childCount;
        vector.childCount += vector.lengths[row];
        vector.child.ensureSize(vector.childCount, true);
        for (int c = 0; c < obj.size(); ++c) {
            childrenConverter.convert(obj.get(c), vector.child,
                    (int) vector.offsets[row] + c);
        }
    }
}
 
Example 4
Source File: JsonUtil.java    From telekom-workflow-engine with MIT License 6 votes vote down vote up
private static Collection<?> deconvertCollection( JsonElement element, Class<?> type, Class<?> elementType ){
    JsonArray array = element.getAsJsonArray();
    if( ARRAYS_ASLIST_CLASS.equals( type ) ){
        Object[] values = new Object[array.size()];
        for( int i = 0; i < array.size(); i++ ){
            Object arrayElement = deconvert( array.get( i ), elementType );
            values[i] = arrayElement;
        }
        return Arrays.asList( values );
    }
    else if( SINGLETON_LIST_CLASS.equals( type ) ){
        return Collections.singletonList( deconvert( array.get( 0 ),
                elementType ) );
    }
    else if( SINGLETON_SET_CLASS.equals( type ) ){
        return Collections.singleton( deconvert( array.get( 0 ), elementType ) );
    }
    else{
        @SuppressWarnings("unchecked")
        Collection<Object> collection = (Collection<Object>)instantiate( type );
        for( int i = 0; i < array.size(); i++ ){
            collection.add( deconvert( array.get( i ), elementType ) );
        }
        return collection;
    }
}
 
Example 5
Source File: MongoUtil.java    From game-server with MIT License 6 votes vote down vote up
/**
 * json 数组转文档
 *
 * @param jsonStr
 * @return
 */
public static List<Object> getDocuments(String jsonStr, String... type) {
    JsonParser parser = new JsonParser();
    JsonElement jsonElement = parser.parse(jsonStr);
    if (jsonElement.isJsonArray()) {
        JsonArray jsonArray = jsonElement.getAsJsonArray();
        List<Object> list = new ArrayList<>();
        jsonArray.forEach(element -> {
            if (element.isJsonObject()) {
                Document d = new Document();
                for (Entry<String, JsonElement> entry : element.getAsJsonObject().entrySet()) {
                    d.append(entry.getKey(), getRealValue(entry.getValue().toString(), type));   //TODO 数据类型检查
                }
                list.add(d);
            } else if (element.isJsonPrimitive()) {
                list.add(getBsonValue(getRealValue(element.getAsString(), type)));
            } else {
                LOGGER.warn("{}数据复杂,不支持多重嵌套", jsonStr);
            }
        });
        return list;
    }
    LOGGER.warn("{}不是json数组", jsonStr);
    return null;
}
 
Example 6
Source File: JsonDeserializer.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
/**
 * Search an array inside a JSON string matching the input path expression and convert each element using a function
 *
 * @param jsonString an encoded JSON string
 * @param function function to parse each element
 * @param paths path fragments
 * @return an array of values
 * @throws JsonPathNotFoundException if json path is invalid
 * @throws IOException               if the underlying input source has problems
 *                                   during parsing
 */
@SuppressWarnings("unchecked")
public static <T> T[] getArrayValue(String jsonString, Function<JsonElement, T> function, String... paths)
    throws JsonPathNotFoundException,
    IOException {
    JsonElement jsonNode = getChildNode(jsonString, paths);
    if (jsonNode != null && jsonNode.isJsonArray()) {
        JsonArray array = jsonNode.getAsJsonArray();
        Object[] values = new Object[array.size()];
        for (int i = 0; i < array.size(); i++) {
            values[i] = function.apply(array.get(i));
        }
        return (T[]) values;
    }
    throw new JsonPathNotFoundException();
}
 
Example 7
Source File: JsonParserProjects.java    From android-galaxyzoo with GNU General Public License v3.0 6 votes vote down vote up
private List<ZooniverseClient.Answer> deserializeAnswersFromJsonElement(final JsonElement jsonElement) {
    final JsonArray jsonArray = jsonElement.getAsJsonArray();
    if (jsonArray == null) {
        return null;
    }

    // Parse each answer:
    final List<ZooniverseClient.Answer> answers = new ArrayList<>();
    for (final JsonElement jsonAnswer : jsonArray) {
        if (jsonAnswer == null) {
            continue;
        }

        final ZooniverseClient.Answer answer = deserializeAnswerFromJsonElement(jsonAnswer);
        answers.add(answer);
    }

    return answers;
}
 
Example 8
Source File: MCRLabelSetTypeAdapter.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
public MCRLabelSetWrapper deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
    throws JsonParseException {
    Set<MCRLabel> labels = new HashSet<>();
    for (JsonElement jsonElement : json.getAsJsonArray()) {
        JsonObject labelJsonObject = jsonElement.getAsJsonObject();
        MCRLabel label = jsonLabelToMCRLabel(labelJsonObject);
        if (label != null) {
            labels.add(label);
        } else {
            LOGGER.warn("Unable to add label with empty lang or text: {}", labelJsonObject);
        }
    }
    return new MCRLabelSetWrapper(labels);
}
 
Example 9
Source File: MXDParser.java    From sldeditor with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Process fields.
 *
 * @param layerName the layer name
 * @param fieldArrayElement the field array element
 * @return the list
 */
private List<DataSourceFieldInterface> processFields(String layerName, JsonElement fieldArrayElement)
{
    List<DataSourceFieldInterface> fieldList = new ArrayList<DataSourceFieldInterface>();

    if(fieldArrayElement != null)
    {
        JsonArray fieldArray = fieldArrayElement.getAsJsonArray();

        for(int index = 0; index < fieldArray.size(); index ++)
        {
            JsonObject fieldObject = null;

            try
            {
                fieldObject = fieldArray.get(index).getAsJsonObject();
            }
            catch(IllegalStateException e)
            {
                ConsoleManager.getInstance().error(this, "Layer : " + layerName);
                ConsoleManager.getInstance().exception(this, e);
            }

            if(fieldObject != null)
            {
                Class<?> fieldType = convertFieldType(fieldObject.get("type").getAsString());

                DataSourceField esriField = new DataSourceField(fieldObject.get("field").getAsString(),
                        fieldType);

                fieldList.add(esriField);
            }
        }
    }

    return fieldList;
}
 
Example 10
Source File: MergeJsonBuilder.java    From java-slack-sdk with MIT License 5 votes vote down vote up
private static void mergeJsonObjects(
        JsonObject leftObj,
        JsonObject rightObj,
        ConflictStrategy conflictStrategy) throws JsonConflictException {

    for (Map.Entry<String, JsonElement> rightEntry : rightObj.entrySet()) {
        String rightKey = rightEntry.getKey();
        JsonElement rightVal = rightEntry.getValue();
        if (leftObj.has(rightKey)) {
            //conflict
            JsonElement leftVal = leftObj.get(rightKey);
            if (leftVal.isJsonArray() && rightVal.isJsonArray()) {
                JsonArray leftArr = leftVal.getAsJsonArray();
                JsonArray rightArr = rightVal.getAsJsonArray();
                for (int i = 0; i < rightArr.size(); i++) {
                    JsonElement rightArrayElem = rightArr.get(i);
                    if (!leftArr.contains(rightArrayElem)) {
                        // remove temporarily added an empty string
                        if (rightArrayElem.isJsonObject()
                                && leftArr.size() == 1
                                && leftArr.get(i).isJsonPrimitive()
                                && leftArr.get(i).getAsString().equals("")) {
                            leftArr.remove(0);
                        }
                        leftArr.add(rightArrayElem);
                    }
                }
            } else if (leftVal.isJsonObject() && rightVal.isJsonObject()) {
                //recursive merging
                mergeJsonObjects(leftVal.getAsJsonObject(), rightVal.getAsJsonObject(), conflictStrategy);
            } else {//not both arrays or objects, normal merge with conflict resolution
                handleMergeConflict(rightKey, leftObj, leftVal, rightVal, conflictStrategy);
            }
        } else {//no conflict, add to the object
            leftObj.add(rightKey, rightVal);
        }
    }
}
 
Example 11
Source File: DiagnosticsPathNode.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public ArrayList<DiagnosticsNode> getChildren() {
  final ArrayList<DiagnosticsNode> children = new ArrayList<>();
  final JsonElement childrenElement = json.get("children");
  if (childrenElement.isJsonNull()) {
    return children;
  }
  final JsonArray childrenJson = childrenElement.getAsJsonArray();
  for (int i = 0; i < childrenJson.size(); ++i) {
    children.add(new DiagnosticsNode(childrenJson.get(i).getAsJsonObject(), inspectorService, false, null));
  }
  return children;
}
 
Example 12
Source File: EitherTypeAdapter.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean test(JsonElement t) {
	if (elementChecker.test(t))
		return true;
	if (t.isJsonArray()) {
		JsonArray array = t.getAsJsonArray();
		if (array.size() == 0)
			return resultIfEmpty;
		for (JsonElement e : array) {
			if (elementChecker.test(e))
				return true;
		}
	}
	return false;
}
 
Example 13
Source File: CocoMetadata.java    From djl with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public Rectangle deserialize(
        JsonElement json, Type typeOfT, JsonDeserializationContext ctx) {
    JsonArray array = json.getAsJsonArray();
    return new Rectangle(
            array.get(0).getAsDouble(), array.get(1).getAsDouble(),
            array.get(2).getAsDouble(), array.get(3).getAsDouble());
}
 
Example 14
Source File: SpecUtils.java    From trimou with Apache License 2.0 5 votes vote down vote up
private static Object getJsonArrayElementValue(JsonElement element) {

        JsonArray array = element.getAsJsonArray();
        List<Object> values = new ArrayList<>(array.size());
        for (JsonElement jsonElement : array) {
            values.add(getJsonElementValue(jsonElement));
        }
        return values;
    }
 
Example 15
Source File: GsonObjectDeserializer.java    From qaf with MIT License 5 votes vote down vote up
public static Object read(JsonElement in) {

		if (in.isJsonArray()) {
			List<Object> list = new ArrayList<Object>();
			JsonArray arr = in.getAsJsonArray();
			for (JsonElement anArr : arr) {
				list.add(read(anArr));
			}
			return list;
		} else if (in.isJsonObject()) {
			Map<String, Object> map = new LinkedTreeMap<String, Object>();
			JsonObject obj = in.getAsJsonObject();
			Set<Map.Entry<String, JsonElement>> entitySet = obj.entrySet();
			for (Map.Entry<String, JsonElement> entry : entitySet) {
				map.put(entry.getKey(), read(entry.getValue()));
			}
			return map;
		} else if (in.isJsonPrimitive()) {
			JsonPrimitive prim = in.getAsJsonPrimitive();
			if (prim.isBoolean()) {
				return prim.getAsBoolean();
			} else if (prim.isString()) {
				return prim.getAsString();
			} else if (prim.isNumber()) {
				if (prim.getAsString().contains("."))
					return prim.getAsDouble();
				else {
					return prim.getAsLong();
				}
			}
		}
		return null;
	}
 
Example 16
Source File: InvokeSc.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
public InvokeSc(JsonObject deploy, boolean standalone, String namespace, String mainComposite,
        File applicationDir) throws URISyntaxException, IOException {
    super();
   
    this.namespace = namespace == null? "": namespace;
    this.mainComposite = mainComposite;
    this.applicationDir = applicationDir;
   
    
    installDir = Util.getStreamsInstall(deploy, ContextProperties.COMPILE_INSTALL_DIR);
    if (deploy.has(ContextProperties.SC_OPTIONS)) {
        JsonElement opts = deploy.get(ContextProperties.SC_OPTIONS);
        if (opts.isJsonArray()) {
            scOptions = new ArrayList<>();
            for (JsonElement e : opts.getAsJsonArray()) {
                scOptions.add(e.getAsString());
            }
        } else {
            scOptions = Collections.singletonList(opts.getAsString());
        }
    } else {
        scOptions = Collections.emptyList();
    }
    
    // Version 4.2 onwards deprecates standalone compiler option
    // so don't use it to avoid warnings.
    if (Util.getStreamsInstall().equals(installDir)) {
        if (Util.versionAtLeast(4, 2, 0))
            standalone = false;
    } else {
        // TODO: get version of compile install to be used
    }
    this.standalone = standalone;
    
    addFunctionalToolkit();
}
 
Example 17
Source File: QuestionListDeserializer.java    From slr-toolkit with Eclipse Public License 1.0 5 votes vote down vote up
public List<Question<?>> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) {
	List<Question<?>> vals = new LinkedList<Question<?>>();
	System.out.println("using deser");
	if (json.isJsonArray()) {
		for (JsonElement e : json.getAsJsonArray()) {
			vals.add((Question<?>) ctx.deserialize(e, Question.class));
		}
	} else if (json.isJsonObject()) {
		vals.add((Question<?>) ctx.deserialize(json, Question.class));
	} else {
		throw new RuntimeException("Unexpected JSON type: " + json.getClass());
	}
	return vals;
}
 
Example 18
Source File: DocumentRepository.java    From spline with Apache License 2.0 5 votes vote down vote up
@Override
public Document deserialize(JsonElement json, Type typeOfT,
                            JsonDeserializationContext context) {

    JsonObject obj = json.getAsJsonObject();
    JsonElement currentLayerEl = obj.remove(CURRENT_LAYER);

    Document document = g.fromJson(obj, Document.class);
    LayerGroup root = document.getRoot();

    if (root != null && currentLayerEl != null) {
        Layer currentLayer = null;
        if (currentLayerEl.isJsonArray()) {
            JsonArray jsonIds = currentLayerEl.getAsJsonArray();

            SelectionGroup selection = new SelectionGroup();
            for (JsonElement el : jsonIds) {
                UUID id = UUID.fromString(el.getAsString());
                Layer l = root.findLayerById(id);
                if (l != null) {
                    selection.addLayer(l);
                }
            }
            currentLayer = selection;
        } else {
            UUID currentLayerId = UUID.fromString(currentLayerEl.getAsString());
            currentLayer = root.findLayerById(currentLayerId);
        }

        document.setCurrentLayer(currentLayer);
    }
    return document;
}
 
Example 19
Source File: JsonStringToJsonIntermediateConverter.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Take in an input schema of type string, the schema must be in JSON format
 * @return a JsonArray representation of the schema
 */
@Override
public JsonArray convertSchema(String inputSchema, WorkUnitState workUnit)
    throws SchemaConversionException {
  this.unpackComplexSchemas =
      workUnit.getPropAsBoolean(UNPACK_COMPLEX_SCHEMAS_KEY, DEFAULT_UNPACK_COMPLEX_SCHEMAS_KEY);

  JsonParser jsonParser = new JsonParser();
  log.info("Schema: " + inputSchema);
  JsonElement jsonSchema = jsonParser.parse(inputSchema);
  return jsonSchema.getAsJsonArray();
}
 
Example 20
Source File: DepLoader.java    From WirelessRedstone with MIT License 4 votes vote down vote up
private void loadJSonArr(JsonElement root) throws IOException {
    for (JsonElement node : root.getAsJsonArray())
        loadJson(node.getAsJsonObject());
}