Java Code Examples for com.google.gson.JsonElement

The following are top voted examples for showing how to use com.google.gson.JsonElement. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GSB-2017-Android   File: ClientsNetworkCalls.java   Source Code and License 7 votes vote down vote up
public static Observable<List<Client>> getAllClients() {
    ClientsService service = ServiceGenerator.createService(ClientsService.class);
    return service.getAllClients(UrlManager.getAllClientsURL())
            .flatMap(new Function<JsonElement, Observable<List<Client>>>() {
                @Override
                public Observable<List<Client>> apply(JsonElement jsonElement) throws Exception {
                    if(jsonElement != null) {
                        Log.i("Get All Clients" , "JSON: "+jsonElement.toString());
                        if(jsonElement.isJsonArray()) {
                            List<Client> clients = Client.ClientsListParser.fromJsonArray(jsonElement.getAsJsonArray());
                            return Observable.just(clients);
                        } else {
                            return Observable.error(new Exception("Expected a JSON Array"));
                        }
                    } else {
                        return Observable.just((List<Client>) new ArrayList<Client>());
                    }
                }
            }).observeOn(AndroidSchedulers.mainThread());
}
 
Example 2
Project: cr-private-server   File: GsonUtils.java   Source Code and License 6 votes vote down vote up
private static void handleMergeConflict(String key, JsonObject leftObj, JsonElement leftVal, JsonElement rightVal, ConflictStrategy conflictStrategy)
		throws JsonObjectExtensionConflictException {
	{
		switch (conflictStrategy) {
		case PREFER_FIRST_OBJ:
			break;//do nothing, the right val gets thrown out
		case PREFER_SECOND_OBJ:
			leftObj.add(key, rightVal);//right side auto-wins, replace left val with its val
			break;
		case PREFER_NON_NULL:
			//check if right side is not null, and left side is null, in which case we use the right val
			if (leftVal.isJsonNull() && !rightVal.isJsonNull()) {
				leftObj.add(key, rightVal);
			}//else do nothing since either the left value is non-null or the right value is null
			break;
		case THROW_EXCEPTION:
			throw new JsonObjectExtensionConflictException("Key " + key + " exists in both objects and the conflict resolution strategy is " + conflictStrategy);
		default:
			throw new UnsupportedOperationException("The conflict strategy " + conflictStrategy + " is unknown and cannot be processed");
		}
	}
}
 
Example 3
Project: CustomWorldGen   File: ModelBlock.java   Source Code and License 6 votes vote down vote up
private Map<String, String> getTextures(JsonObject object)
{
    Map<String, String> map = Maps.<String, String>newHashMap();

    if (object.has("textures"))
    {
        JsonObject jsonobject = object.getAsJsonObject("textures");

        for (Entry<String, JsonElement> entry : jsonobject.entrySet())
        {
            map.put(entry.getKey(), ((JsonElement)entry.getValue()).getAsString());
        }
    }

    return map;
}
 
Example 4
Project: kheera-testrunner-android   File: TableConverter.java   Source Code and License 6 votes vote down vote up
static <T> List<T> toList(PickleTable dataTable, Type itemType, JsonElement testData) {
    List<T> result = new ArrayList<T>();
    List<String> keys = convertTopCellsToFieldNames(raw(dataTable.getRows().get(0)));
    int count = dataTable.getRows().size();
    for (int i = 1; i < count; i++) {
        List<String> valueRow = raw(dataTable.getRows().get(i));
        T item = (T) SuperReflect.on((Class) itemType).create().get();
        int j = 0;
        for (String cell : valueRow) {
            SuperReflect.on(item).set(keys.get(j), cell);
            j++;
        }
        result.add(item);
    }
    return Collections.unmodifiableList(result);
}
 
Example 5
Project: CustomWorldGen   File: SetAttributes.java   Source Code and License 6 votes vote down vote up
public SetAttributes deserialize(JsonObject object, JsonDeserializationContext deserializationContext, LootCondition[] conditionsIn)
{
    JsonArray jsonarray = JsonUtils.getJsonArray(object, "modifiers");
    SetAttributes.Modifier[] asetattributes$modifier = new SetAttributes.Modifier[jsonarray.size()];
    int i = 0;

    for (JsonElement jsonelement : jsonarray)
    {
        asetattributes$modifier[i++] = SetAttributes.Modifier.deserialize(JsonUtils.getJsonObject(jsonelement, "modifier"), deserializationContext);
    }

    if (asetattributes$modifier.length == 0)
    {
        throw new JsonSyntaxException("Invalid attribute modifiers array; cannot be empty");
    }
    else
    {
        return new SetAttributes(conditionsIn, asetattributes$modifier);
    }
}
 
Example 6
Project: DHIS2-fhir-lab-app   File: FhirMediatorUtilities.java   Source Code and License 6 votes vote down vote up
public static SpecimenFhirMapping getSpecimenMappingAttributes (String filePath) throws Exception
{
    SpecimenFhirMapping specimenAttributeMapping=new SpecimenFhirMapping();
    Gson gson=new Gson();
    try {
        JsonElement json=gson.fromJson(new FileReader(filePath), JsonElement.class);
        String jsonAttributeMappingString=((JsonObject)json).get("specimen_attribute_mapping").toString();
        specimenAttributeMapping=gson.fromJson(jsonAttributeMappingString,SpecimenFhirMapping.class);
        //System.out.print(0);
    }
    catch (Exception exc)
    {
        throw new Exception(exc.toString());
    }
    return specimenAttributeMapping;
}
 
Example 7
Project: kino_system   File: LoadFromJSON.java   Source Code and License 6 votes vote down vote up
public void LoadPersonen(String path) throws FileNotFoundException {
    parser = new JsonParser();
    Object obj = parser.parse(new FileReader(path));

    JsonArray personen = (JsonArray) obj;

    for (JsonElement j : personen) {
        JsonObject jsonObject = j.getAsJsonObject();
        PersonenSammelung.Personen.add(
                new Person(
                        jsonObject.get("id").getAsString(),
                        jsonObject.get("name").getAsString(),
                        jsonObject.get("vorname").getAsString(),
                        jsonObject.get("email").getAsString(),
                        jsonObject.get("telefonnummer").getAsString()
                )
        );

    }
}
 
Example 8
Project: Ghost-Android   File: ConfigurationListDeserializer.java   Source Code and License 6 votes vote down vote up
private ConfigurationParam makeConfigParam(String key, JsonElement value) {
    if (value.isJsonNull()) {
        throw new NullPointerException("value for key '" + key + "' is null!");
    }
    ConfigurationParam param = new ConfigurationParam();
    param.setKey(key);
    String valueStr;
    if (value.isJsonPrimitive() && value.getAsJsonPrimitive().isString()) {
        // toString would return the string with quotes around it which we don't want
        valueStr = value.getAsString();
    } else {
        valueStr = value.toString();
    }
    param.setValue(valueStr);
    return param;
}
 
Example 9
Project: GSB-2017-Android   File: Branch.java   Source Code and License 6 votes vote down vote up
public static Branch fromJsonElement(JsonElement jsonElement) {
    Branch branch = new Branch();
    if(!JsonHelper.isNull(jsonElement ,"brCode")) {
        branch.setCodeBr(jsonElement.getAsJsonObject().get("brCode").getAsInt());
    }
    if(!JsonHelper.isNull(jsonElement ,"brName")) {
        branch.setNameBr(jsonElement.getAsJsonObject().get("brName").getAsString());
    }
    if(!JsonHelper.isNull(jsonElement ,"brTel")) {
        branch.setTelBr(jsonElement.getAsJsonObject().get("brTel").getAsString());
    }
    if(!JsonHelper.isNull(jsonElement ,"brAddress")) {
        branch.setAddressBr(jsonElement.getAsJsonObject().get("brAddress").getAsString());
    }
    return branch;
}
 
Example 10
Project: rtc-workitem-bulk-mover-service   File: ProjectAreaTypeService.java   Source Code and License 6 votes vote down vote up
public void execute() throws IOException, URISyntaxException, AuthenticationException {
    String pa = restRequest.getParameterValue("project-area");
    Map<String, JsonElement> typeMap = new TreeMap<String, JsonElement>();
    try {
        IProjectAreaHandle targetArea = ProjectAreaHelpers.getProjectArea(pa, parentService);
        if(targetArea == null) {
            response.setStatus(400);
            return;
        }
        IWorkItemServer serverService = parentService.getService(IWorkItemServer.class);
        List<IWorkItemType> types = WorkItemTypeHelpers.getWorkItemTypes(targetArea, serverService, new NullProgressMonitor());
        for(IWorkItemType type : types) {
            JsonObject typeObject = new JsonObject();
            typeObject.addProperty("id", type.getIdentifier());
            typeObject.addProperty("name", type.getDisplayName());
            typeMap.put(type.getDisplayName(), typeObject);
        }
    } catch (TeamRepositoryException e) {
        response.setStatus(500);
    }
    response.getWriter().write(new Gson().toJson(typeMap.values()));
}
 
Example 11
Project: incubator-sdap-mudrod   File: HybridRecommendation.java   Source Code and License 6 votes vote down vote up
/**
 * Method of converting hashmap to JSON
 *
 * @param wordweights a map from related metadata to weights
 * @param num         the number of converted elements
 * @return converted JSON object
 */
protected JsonElement mapToJson(Map<String, Double> wordweights, int num) {
  Gson gson = new Gson();

  List<JsonObject> nodes = new ArrayList<>();
  Set<String> words = wordweights.keySet();
  int i = 0;
  for (String wordB : words) {
    JsonObject node = new JsonObject();
    node.addProperty("name", wordB);
    node.addProperty("weight", wordweights.get(wordB));
    nodes.add(node);

    i += 1;
    if (i >= num) {
      break;
    }
  }

  String nodesJson = gson.toJson(nodes);
  JsonElement nodesElement = gson.fromJson(nodesJson, JsonElement.class);

  return nodesElement;
}
 
Example 12
Project: abhot   File: DataPointsParser.java   Source Code and License 6 votes vote down vote up
private String findType(JsonElement value) throws ValidationException
{
	if (!value.isJsonPrimitive()){
		throw new ValidationException("value is an invalid type");
	}

	JsonPrimitive primitiveValue = (JsonPrimitive) value;
	if (primitiveValue.isNumber() || (primitiveValue.isString() && Util.isNumber(value.getAsString())))
	{
		String v = value.getAsString();

		if (!v.contains("."))
		{
			return "long";
		}
		else
		{
			return "double";
		}
	}
	else
		return "string";
}
 
Example 13
Project: Phoenix-for-VK   File: CommentDtoAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public VKApiComment deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    JsonObject root = json.getAsJsonObject();
    VKApiComment dto = new VKApiComment();

    dto.id = optInt(root, "id");
    dto.from_id = optInt(root, "from_id");

    if(dto.from_id == 0){
        dto.from_id = optInt(root, "owner_id");
    }

    dto.date = optLong(root, "date");
    dto.text = optString(root, "text");
    dto.reply_to_user = optInt(root, "reply_to_user");
    dto.reply_to_comment = optInt(root, "reply_to_comment");

    if(root.has("attachments")){
        dto.attachments = context.deserialize(root.get("attachments"), VkApiAttachments.class);
    }

    if(root.has("likes")){
        JsonObject likesRoot = root.getAsJsonObject("likes");
        dto.likes = optInt(likesRoot, "count");
        dto.user_likes = optIntAsBoolean(likesRoot, "user_likes");
        dto.can_like = optIntAsBoolean(likesRoot, "can_like");
    }

    dto.can_edit = optIntAsBoolean(root, "can_edit");
    return dto;
}
 
Example 14
Project: ultimate-geojson   File: PointDeserializer.java   Source Code and License 5 votes vote down vote up
@Override
public PointDto deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {

	PointDto point = new PointDto();

	JsonObject asJsonObject = json.getAsJsonObject();
	JsonElement jsonElement = asJsonObject.get("coordinates");
	PositionDto positionDto = context.deserialize(jsonElement, PositionDto.class);
	point.setPosition(positionDto);

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

	return point;
}
 
Example 15
Project: MineIDE   File: DataTypeList.java   Source Code and License 5 votes vote down vote up
@Override
public DataManager fromJson(final JsonElement json)
{
    DataManager dt = new DataManager();
    dt.fromJson(json);
    return dt;
}
 
Example 16
Project: datarouter   File: JsonDatabeanTool.java   Source Code and License 5 votes vote down vote up
private static <PK extends PrimaryKey<PK>> void primaryKeyFromJson(PK pk, Fielder<PK> fielder, JsonObject json){
	if(json == null){
		return;
	}
	List<Field<?>> fields = fielder.getFields(pk);
	for(Field<?> field : fields){
		String jsonFieldName = field.getKey().getColumnName();
		JsonElement jsonValue = json.get(jsonFieldName);
		if(jsonValue == null || jsonValue instanceof JsonNull){//PK fields are required
			throw new IllegalStateException(json + " does not contain required key " + jsonFieldName);
		}
		Object value = field.parseStringEncodedValueButDoNotSet(jsonValue.getAsString());
		field.setUsingReflection(pk, value);
	}
}
 
Example 17
Project: modName   File: Settings.java   Source Code and License 5 votes vote down vote up
static <T extends IJsonMappable> void readJsonableMap(JsonObject o, LinkedHashMap<String, T> list, String tagname, Class<T> clazz) {
    list.clear();
    if (o.has(tagname)) {
        JsonArray g = JsonUtil.getAsArray(o, tagname); //o.getAsJsonArray(tagname);
        for (JsonElement element : g) {
            T def = IJsonable.create(clazz);
            JsonObject eo;
            /*try {
                eo = element.getAsJsonObject();
            } catch (Exception e) {
                return;
            }*/
            eo = JsonUtil.asObject(element);
            def.fromJson(eo);
            list.put(def.getMapKey(), def);
        }
    }

}
 
Example 18
Project: BaseClient   File: JsonUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the string value of the given JsonElement.  Expects the second parameter to be the name of the element's
 * field if an error message needs to be thrown.
 */
public static String getString(JsonElement p_151206_0_, String p_151206_1_)
{
    if (p_151206_0_.isJsonPrimitive())
    {
        return p_151206_0_.getAsString();
    }
    else
    {
        throw new JsonSyntaxException("Expected " + p_151206_1_ + " to be a string, was " + toString(p_151206_0_));
    }
}
 
Example 19
Project: GSB-2017-Android   File: Brand.java   Source Code and License 5 votes vote down vote up
public static Brand fromJsonElement(JsonElement jsonElement) {
    Brand brand = new Brand();
    if(!JsonHelper.isNull(jsonElement ,"brdCode")) {
        brand.setCodeBrd(jsonElement.getAsJsonObject().get("brdCode").getAsInt());
    }
    if(!JsonHelper.isNull(jsonElement ,"brdName")) {
        brand.setNameBrd(jsonElement.getAsJsonObject().get("brdName").getAsString());
    }
    if(!JsonHelper.isNull(jsonElement ,"brdStatus")) {
        brand.setStatusBrd(jsonElement.getAsJsonObject().get("brdStatus").getAsBoolean());
    }
    return brand;
}
 
Example 20
Project: Backmemed   File: ItemOverride.java   Source Code and License 5 votes vote down vote up
public ItemOverride deserialize(JsonElement p_deserialize_1_, Type p_deserialize_2_, JsonDeserializationContext p_deserialize_3_) throws JsonParseException
{
    JsonObject jsonobject = p_deserialize_1_.getAsJsonObject();
    ResourceLocation resourcelocation = new ResourceLocation(JsonUtils.getString(jsonobject, "model"));
    Map<ResourceLocation, Float> map = this.makeMapResourceValues(jsonobject);
    return new ItemOverride(resourcelocation, map);
}
 
Example 21
Project: TruenoNPC   File: TruenoNPC_v1_9_r1.java   Source Code and License 5 votes vote down vote up
private JsonObject getChacheFile(Plugin plugin){
    File file = new File(plugin.getDataFolder().getPath()+"/truenonpcdata.json");
    if(file.exists()){
        try{
            JsonParser parser = new JsonParser();
            JsonElement jsonElement = parser.parse(new FileReader(file));
            return jsonElement.getAsJsonObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }else return null;
}
 
Example 22
Project: datarouter   File: StringEnumSerializer.java   Source Code and License 5 votes vote down vote up
@Override
public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException{
	@SuppressWarnings("unchecked")
	Class<T> classOfT = (Class<T>) typeOfT;
	T enumValue = classOfT.getEnumConstants()[0];
	return enumValue.fromPersistentString(json.getAsString());
}
 
Example 23
Project: java-binance-api   File: BinanceApi.java   Source Code and License 5 votes vote down vote up
/**
 * Getting balances - part of account information
 * @return map of wallet assets structure
 * @throws BinanceApiException  in case of any error
 */
public Map<String, BinanceWalletAsset> balancesMap() throws BinanceApiException {
    Map<String, BinanceWalletAsset> mapAssets = new ConcurrentHashMap<>();
    for (JsonElement el : balances()) {
        BinanceWalletAsset w = new BinanceWalletAsset(el.getAsJsonObject());
        mapAssets.put(w.getAsset(), w);
    }
    return mapAssets;
}
 
Example 24
Project: AgarMC   File: Utils.java   Source Code and License 5 votes vote down vote up
public static Location getLocation(JsonElement object)
{
    JsonObject json = object.getAsJsonObject();
    World world = AgarMC.get().getWorld();
    double x = json.get("x").getAsDouble() + 0.5;
    double y = json.get("y").getAsDouble();
    double z = json.get("z").getAsDouble() + 0.5;
    try
    {
        float yaw = (float)json.get("yaw").getAsDouble();
        float pitch = (float)json.get("pitch").getAsDouble();
        return new Location(world, x, y, z, yaw, pitch);
    }
    catch (UnsupportedOperationException | NullPointerException ex)
    {
        return new Location(world, x, y, z);
    }
}
 
Example 25
Project: helper   File: VectorSerializers.java   Source Code and License 5 votes vote down vote up
public static Vector4l deserialize4l(JsonElement element) {
    return new Vector4l(
            element.getAsJsonObject().get("x").getAsLong(),
            element.getAsJsonObject().get("y").getAsLong(),
            element.getAsJsonObject().get("z").getAsLong(),
            element.getAsJsonObject().get("w").getAsLong()
    );
}
 
Example 26
Project: InControl   File: LootRule.java   Source Code and License 5 votes vote down vote up
public static LootRule parse(JsonElement element) {
    if (element == null) {
        return null;
    } else {
        AttributeMap map = FACTORY.parse(element);
        return new LootRule(map);
    }
}
 
Example 27
Project: ParsingPlayer   File: YoukuExtractor.java   Source Code and License 5 votes vote down vote up
private Map<Integer, Stream> getSegMap(JsonObject data) throws UnsupportedEncodingException {
    HashMap<Integer, Stream> streamMap = new HashMap<>();
    JsonArray streams = data.getAsJsonArray("stream");
    for (JsonElement streamJson : streams) {
        if (streamJson.getAsJsonObject().get("channel_type") != null && streamJson.getAsJsonObject().get("channel_type").getAsString().equals("tail"))
            continue;
        List<Seg> segList = new ArrayList<>();

        JsonArray segJsons = streamJson.getAsJsonObject().getAsJsonArray("segs");
        for (JsonElement segJson : segJsons) {
            String url = segJson.getAsJsonObject().get("cdn_url").getAsString();
            double duration = segJson.getAsJsonObject().get("total_milliseconds_audio").getAsInt() / 1000;
            Seg seg = new Seg(url, duration);
            segList.add(seg);
        }

        int size = streamJson.getAsJsonObject().get("size").getAsInt();
        int height = streamJson.getAsJsonObject().get("height").getAsInt();
        int width = streamJson.getAsJsonObject().get("width").getAsInt();
        Stream stream = new Stream(segList, size, height, width);
        stream.setSize(size);
        streamMap.put(calQualityByHeight(height), stream);
    }
    return streamMap;
}
 
Example 28
Project: bireme   File: DebeziumPipeLine.java   Source Code and License 5 votes vote down vote up
public DebeziumRecord(String topic, JsonObject payLoad) {
  this.topic = topic;
  char op = payLoad.get("op").getAsCharacter();
  this.produceTime = payLoad.get("ts_ms").getAsLong();

  JsonElement element = null;
  switch (op) {
    case 'r':
    case 'c':
      type = RowType.INSERT;
      element = payLoad.get("after");
      break;

    case 'u':
      type = RowType.UPDATE;
      element = payLoad.get("after");
      break;

    case 'd':
      type = RowType.DELETE;
      element = payLoad.get("before");
      break;
  }

  this.data = element.getAsJsonObject();
}
 
Example 29
Project: Wurst-MC-1.12   File: Updater.java   Source Code and License 5 votes vote down vote up
private boolean containsCompatibleAsset(JsonArray assets)
{
	for(JsonElement asset : assets)
	{
		if(!asset.getAsJsonObject().get("name").getAsString()
			.endsWith("MC" + WMinecraft.VERSION
				+ (WMinecraft.OPTIFINE ? "-OF" : "") + ".jar"))
			continue;
		
		return true;
	}
	
	return false;
}
 
Example 30
Project: modName   File: JsonUtil.java   Source Code and License 5 votes vote down vote up
private static <T> T getValue(JsonElement element, T compared) throws IllegalStateException, ClassCastException, IllegalArgumentException {
    if (compared instanceof Double) {
        return (T)(new Double(element.getAsDouble()));
    }
    else if (compared instanceof Integer) {
        return (T)(new Integer(element.getAsInt()));
    }
    else if (compared instanceof JsonObject) {
        return (T)element.getAsJsonObject();
    }
    else if (compared instanceof JsonArray) {
        return (T)element.getAsJsonArray();
    }
    else if (compared instanceof String) {
        return (T)element.getAsString();
    }
    else if (compared instanceof Boolean) {
        return (T)(new Boolean(element.getAsBoolean()));
    }

    throw new IllegalArgumentException();
}
 
Example 31
Project: ctsms   File: CommonUtil.java   Source Code and License 5 votes vote down vote up
private static void getSvgPath(JsonElement path, StringBuilder d) {
	if (path != null && !path.isJsonNull()) {
		if (path.isJsonArray()) {
			Iterator<JsonElement> linesIt = path.getAsJsonArray().iterator();
			while (linesIt.hasNext()) {
				if (d.length() > 0) {
					d.append(" ");
				}
				getSvgPath(linesIt.next(), d);
			}
		} else {
			d.append(path.getAsString());
		}
	}
}
 
Example 32
Project: MessageOnTap_API   File: SparseArrayTypeAdapter.java   Source Code and License 5 votes vote down vote up
@Override
public SparseArray<T> read(JsonReader jsonReader) throws IOException {
    if (jsonReader.peek() == JsonToken.NULL) {
        jsonReader.nextNull();
        return null;
    }
    SparseArray<Object> temp = gson.fromJson(jsonReader, typeOfSparseArrayOfObject);
    SparseArray<T> result = new SparseArray<>(temp.size());
    int key;
    JsonElement tElement;
    for (int i = 0, size = temp.size(); i < size; ++i) {
        key = temp.keyAt(i);
        tElement = gson.toJsonTree(temp.get(key));
        result.put(key, (T) JSONUtils.jsonToSimpleObject(tElement.toString(), typeOfT));
    }
    return result;
}
 
Example 33
Project: GitHub   File: Convert.java   Source Code and License 5 votes vote down vote up
public static String formatJson(Object src) {
    try {
        JsonParser jp = new JsonParser();
        JsonElement je = jp.parse(toJson(src));
        return JsonConvertor.getInstance().toJson(je);
    } catch (Exception e) {
        return e.getMessage();
    }
}
 
Example 34
Project: matrix-java-sdk   File: MatrixJsonObject.java   Source Code and License 5 votes vote down vote up
protected String getStringOrNull(JsonObject obj, String field) {
    if (!obj.has(field)) {
        return null;
    }

    JsonElement el = obj.get(field);
    if (el.isJsonNull()) {
        return null;
    }

    return el.getAsString();
}
 
Example 35
Project: Cypher   File: Client.java   Source Code and License 5 votes vote down vote up
private void parsePresenceEvents(JsonObject syncData) {
	if(syncData.has("presence")) {
		JsonObject presenceData = syncData.get("presence").getAsJsonObject();
		if(presenceData.has("events")) {
			JsonArray presenceEvents = presenceData.get("events").getAsJsonArray();
			for(JsonElement eventElement : presenceEvents) {
				JsonObject eventObject = eventElement.getAsJsonObject();
				if(eventObject.has("sender")) {
					User user = users.get(eventObject.get("sender").getAsString());
					user.update(eventObject);
				}
			}
		}
	}
}
 
Example 36
Project: IPE-LWM2M   File: RegistrationSerializer.java   Source Code and License 5 votes vote down vote up
@Override
public JsonElement serialize(Registration src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject element = new JsonObject();

    element.addProperty("endpoint", src.getEndpoint());
    element.addProperty("registrationId", src.getId());
    element.add("registrationDate", context.serialize(src.getRegistrationDate()));
    element.add("lastUpdate", context.serialize(src.getLastUpdate()));
    element.addProperty("address", src.getAddress().getHostAddress() + ":" + src.getPort());
    element.addProperty("smsNumber", src.getSmsNumber());
    element.addProperty("lwM2mVersion", src.getLwM2mVersion());
    element.addProperty("lifetime", src.getLifeTimeInSec());
    element.addProperty("bindingMode", src.getBindingMode().toString());
    element.add("rootPath", context.serialize(src.getRootPath()));
    element.add("objectLinks", context.serialize(src.getSortedObjectLinks()));
    element.add("secure", context.serialize(src.getRegistrationEndpointAddress().getPort() == securePort));
    element.add("additionalRegistrationAttributes", context.serialize(src.getAdditionalRegistrationAttributes()));

    return element;
}
 
Example 37
Project: graphql_java_gen   File: Generated.java   Source Code and License 5 votes vote down vote up
public IntegerEntry(JsonObject fields) throws SchemaViolationError {
    for (Map.Entry<String, JsonElement> field : fields.entrySet()) {
        String key = field.getKey();
        String fieldName = getFieldName(key);
        switch (fieldName) {
            case "key": {
                responseData.put(key, jsonAsString(field.getValue(), key));

                break;
            }

            case "ttl": {
                LocalDateTime optional1 = null;
                if (!field.getValue().isJsonNull()) {
                    optional1 = LocalDateTime.parse(jsonAsString(field.getValue(), key));
                }

                responseData.put(key, optional1);

                break;
            }

            case "value": {
                responseData.put(key, jsonAsInteger(field.getValue(), key));

                break;
            }

            case "__typename": {
                responseData.put(key, jsonAsString(field.getValue(), key));
                break;
            }
            default: {
                throw new SchemaViolationError(this, key, field.getValue());
            }
        }
    }
}
 
Example 38
Project: CustomWorldGen   File: ForgeBlockStateV1.java   Source Code and License 5 votes vote down vote up
public static Quat4f parseAxisRotation(JsonElement e)
{
    if (!e.isJsonObject()) throw new JsonParseException("Axis rotation: object expected, got: " + e);
    JsonObject obj  = e.getAsJsonObject();
    if (obj.entrySet().size() != 1) throw new JsonParseException("Axis rotation: expected single axis object, got: " + e);
    Map.Entry<String, JsonElement> entry = obj.entrySet().iterator().next();
    Quat4f ret = new Quat4f();
    try
    {
        if (entry.getKey().equals("x"))
        {
            ret.set(new AxisAngle4d(1, 0, 0, Math.toRadians(entry.getValue().getAsNumber().floatValue())));
        }
        else if (entry.getKey().equals("y"))
        {
            ret.set(new AxisAngle4d(0, 1, 0, Math.toRadians(entry.getValue().getAsNumber().floatValue())));
        }
        else if (entry.getKey().equals("z"))
        {
            ret.set(new AxisAngle4d(0, 0, 1, Math.toRadians(entry.getValue().getAsNumber().floatValue())));
        }
        else throw new JsonParseException("Axis rotation: expected single axis key, got: " + entry.getKey());
    }
    catch(ClassCastException ex)
    {
        throw new JsonParseException("Axis rotation value: expected number, got: " + entry.getValue());
    }
    return ret;
}
 
Example 39
Project: module-template   File: RestTests.java   Source Code and License 5 votes vote down vote up
private int createIssue(Issue newIssue) throws IOException {
    String json = getExecutor().execute(Request.Post("http://demo.bugify.com/api/issues.json")
            .bodyForm(new BasicNameValuePair("subject", newIssue.getSubject()),
                    new BasicNameValuePair("description", newIssue.getDescription())))
            .returnContent().asString();

    JsonElement parsed = new JsonParser().parse(json);

    return parsed.getAsJsonObject().get("issue_id").getAsInt();
}
 
Example 40
Project: libris   File: URLAzureImageSearcher.java   Source Code and License 5 votes vote down vote up
private ArrayList<String> retrieveTagsFromJson(JsonObject response) {
    JsonArray tagArray = response.getAsJsonArray("tags");
    ArrayList<String> tags = new ArrayList<>();
    for (JsonElement element : tagArray)
        tags.add(element.getAsJsonObject().get("name").getAsString());
    return tags;
}
 
Example 41
Project: device-modbus   File: ModbusHandler.java   Source Code and License 5 votes vote down vote up
private String parseArg(String arguments, ResourceOperation operation, PropertyValue value, String object) {
	// parse the argument string and get the "value" parameter
	JsonObject args;
	String val = null;
	JsonElement jElem = null;
	Boolean passed = true;
	
	// check for parameters from the command
	if(arguments != null){
		args = new JsonParser().parse(arguments).getAsJsonObject();
		jElem = args.get(object);
	}
	
	// if the parameter is passed from the command, use it, otherwise treat parameter as the default
	if (jElem == null || jElem.toString().equals("null")) {
		val = operation.getParameter();
		passed = false;
	} else {
		val = jElem.toString().replace("\"", "");
	}
	
	// if no value is specified by argument or parameter, take the object default from the profile
	if (val == null) {
		val = value.getDefaultValue();
		passed = false;
	}
	
	// if a mapping translation has been specified in the profile, use it
	Map<String,String> mappings = operation.getMappings();
	if (mappings != null && mappings.containsKey(val)) {
		val = mappings.get(val);
		passed = false;
	}
	
	if (!value.mask().equals(BigInteger.ZERO) && passed) {
		val = transform.format(value, val);
	}
	
	return val;
}
 
Example 42
Project: Backmemed   File: ServerStatusResponse.java   Source Code and License 5 votes vote down vote up
public ServerStatusResponse deserialize(JsonElement p_deserialize_1_, Type p_deserialize_2_, JsonDeserializationContext p_deserialize_3_) throws JsonParseException
{
    JsonObject jsonobject = JsonUtils.getJsonObject(p_deserialize_1_, "status");
    ServerStatusResponse serverstatusresponse = new ServerStatusResponse();

    if (jsonobject.has("description"))
    {
        serverstatusresponse.setServerDescription((ITextComponent)p_deserialize_3_.deserialize(jsonobject.get("description"), ITextComponent.class));
    }

    if (jsonobject.has("players"))
    {
        serverstatusresponse.setPlayers((ServerStatusResponse.Players)p_deserialize_3_.deserialize(jsonobject.get("players"), ServerStatusResponse.Players.class));
    }

    if (jsonobject.has("version"))
    {
        serverstatusresponse.setVersion((ServerStatusResponse.Version)p_deserialize_3_.deserialize(jsonobject.get("version"), ServerStatusResponse.Version.class));
    }

    if (jsonobject.has("favicon"))
    {
        serverstatusresponse.setFavicon(JsonUtils.getString(jsonobject, "favicon"));
    }

    return serverstatusresponse;
}
 
Example 43
Project: AmenEye   File: JsonUtils.java   Source Code and License 5 votes vote down vote up
public static NewsContent readJsonNewsContent(String res, String docId) {
    NewsContent newsDetailBean = null;
    try {
        JsonParser parser = new JsonParser();
        JsonObject jsonObj = parser.parse(res).getAsJsonObject();
        JsonElement jsonElement = jsonObj.get(docId);
        if (jsonElement == null) {
            return null;
        }
        newsDetailBean = JsonUtils.deserialize(jsonElement.getAsJsonObject(), NewsContent.class);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return newsDetailBean;
}
 
Example 44
Project: buckaroo   File: RecipeSerializer.java   Source Code and License 5 votes vote down vote up
@Override
public JsonElement serialize(final Recipe recipe, final Type type, final JsonSerializationContext context) {

    Preconditions.checkNotNull(recipe);
    Preconditions.checkNotNull(type);
    Preconditions.checkNotNull(context);

    final JsonObject jsonObject = new JsonObject();

    jsonObject.add("name", context.serialize(recipe.name));
    jsonObject.addProperty("url", recipe.url.toString());
    jsonObject.add("versions", context.serialize(recipe.versions));

    return jsonObject;
}
 
Example 45
Project: Hydroangeas   File: SimpleGameTemplate.java   Source Code and License 5 votes vote down vote up
public SimpleGameTemplate(String id, String gameName, String mapName, int minSlot, int maxSlot, JsonElement options, int weight, boolean isCoupaing)
{
    this.id = id;
    this.gameName = gameName;
    this.mapName = mapName;
    this.minSlot = minSlot;
    this.maxSlot = maxSlot;
    this.options = options;
    this.isCoupaing = isCoupaing;
}
 
Example 46
Project: shuffleboard   File: WidgetSaver.java   Source Code and License 5 votes vote down vote up
@Override
public JsonElement serialize(Widget src, JsonSerializationContext context) {
  JsonObject object = new JsonObject();
  object.addProperty("_type", src.getName());
  for (int i = 0; i < src.getSources().size(); i++) {
    object.addProperty("_source" + i, src.getSources().get(i).getId());
  }
  object.addProperty("_title", src.getTitle());
  for (Property p : src.getProperties()) {
    object.add(p.getName(), context.serialize(p.getValue()));
  }
  return object;
}
 
Example 47
Project: buckaroo   File: ProjectSerializer.java   Source Code and License 5 votes vote down vote up
@Override
public JsonElement serialize(final Project project, final Type type, final JsonSerializationContext context) {

    Preconditions.checkNotNull(project);
    Preconditions.checkNotNull(type);
    Preconditions.checkNotNull(context);

    final JsonObject jsonObject = new JsonObject();

    if (project.name.isPresent()) {
        jsonObject.addProperty("name", project.name.get());
    }

    if (project.target.isPresent()) {
        jsonObject.addProperty("target", project.target.get());
    }

    if (project.license.isPresent()) {
        jsonObject.addProperty("license", project.license.get());
    }

    if (project.dependencies.any()) {
        jsonObject.add("dependencies", context.serialize(project.dependencies));
    }

    return jsonObject;
}
 
Example 48
Project: CustomWorldGen   File: BlockFaceUV.java   Source Code and License 5 votes vote down vote up
public BlockFaceUV deserialize(JsonElement p_deserialize_1_, Type p_deserialize_2_, JsonDeserializationContext p_deserialize_3_) throws JsonParseException
{
    JsonObject jsonobject = p_deserialize_1_.getAsJsonObject();
    float[] afloat = this.parseUV(jsonobject);
    int i = this.parseRotation(jsonobject);
    return new BlockFaceUV(afloat, i);
}
 
Example 49
Project: BaseClient   File: PackMetadataSectionSerializer.java   Source Code and License 5 votes vote down vote up
public JsonElement serialize(PackMetadataSection p_serialize_1_, Type p_serialize_2_, JsonSerializationContext p_serialize_3_)
{
    JsonObject jsonobject = new JsonObject();
    jsonobject.addProperty("pack_format", (Number)Integer.valueOf(p_serialize_1_.getPackFormat()));
    jsonobject.add("description", p_serialize_3_.serialize(p_serialize_1_.getPackDescription()));
    return jsonobject;
}
 
Example 50
Project: odoo-work   File: JsonTreeWriter.java   Source Code and License 5 votes vote down vote up
@Override public JsonWriter endObject() throws IOException {
  if (stack.isEmpty() || pendingName != null) {
    throw new IllegalStateException();
  }
  JsonElement element = peek();
  if (element instanceof JsonObject) {
    stack.remove(stack.size() - 1);
    return this;
  }
  throw new IllegalStateException();
}
 
Example 51
Project: VKMusicUploader   File: AttachmentsFromResults.java   Source Code and License 5 votes vote down vote up
/**
 * Maps queries queriesResults to Attachment strings.
 * @return Attachment strings.
 * @throws IOException If unknown Attachment format is found.
 */
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public List<String> attachments() throws IOException {
    final List<String> list = new ArrayList<>(this.root.size());
    for (final JsonElement element : this.root) {
        list.addAll(
            new AttachmentFormatStrings(element)
                .attachmentStrings()
        );
    }
    return new Array<>(list);
}
 
Example 52
Project: BookWorldClient   File: BookResultsManager.java   Source Code and License 5 votes vote down vote up
public static List<Book> createBooks(JsonObject booksResult) {
    List<Book> books = new ArrayList<>();
    JsonArray jsonArray = booksResult.get("docs").getAsJsonArray();
    int i = 0;
    for (JsonElement jsonElement : jsonArray) {
        if (i > 20) {
            break;
        }
        books.add(createBook(jsonElement));
        i++;
    }
    return books;
}
 
Example 53
Project: sepatools   File: BindingsResults.java   Source Code and License 5 votes vote down vote up
private JsonArray getBindingsArray() {
	JsonElement varArray;
	if (results == null) return null;
	if((varArray=results.get("results")) == null) return null;
	if((varArray=varArray.getAsJsonObject().get("bindings"))==null) return null;
	
	return varArray.getAsJsonArray();	
}
 
Example 54
Project: SurvivalAPI   File: StockupModule.java   Source Code and License 5 votes vote down vote up
@Override
public Map<String, Object> buildFromJson(Map<String, JsonElement> configuration) throws Exception
{
    if (configuration.containsKey("hearts"))
        this.setHeartsAmount(configuration.get("hearts").getAsInt());

    return this.build();
}
 
Example 55
Project: disclosure-android-app   File: OffsetDateTimeTypeAdapterShould.java   Source Code and License 5 votes vote down vote up
@Test public void deserializeJsonToDate() {
  String testJson = "2016-01-01T01:30:15Z";
  JsonElement json = new JsonPrimitive(testJson);

  OffsetDateTime expectedDate = OffsetDateTime.of(2016, 1, 1, 1, 30, 15, 0, ZoneOffset.UTC);
  OffsetDateTime date = adapter.deserialize(json, OffsetDateTime.class, deserializationContext);

  assertThat(date).isEqualTo(expectedDate);
}
 
Example 56
Project: helper   File: VectorSerializers.java   Source Code and License 5 votes vote down vote up
public static Vector3f deserialize3f(JsonElement element) {
    return new Vector3f(
            element.getAsJsonObject().get("x").getAsFloat(),
            element.getAsJsonObject().get("y").getAsFloat(),
            element.getAsJsonObject().get("z").getAsFloat()
    );
}
 
Example 57
Project: CustomWorldGen   File: LootEntry.java   Source Code and License 5 votes vote down vote up
public JsonElement serialize(LootEntry p_serialize_1_, Type p_serialize_2_, JsonSerializationContext p_serialize_3_)
{
    JsonObject jsonobject = new JsonObject();
    if (p_serialize_1_.entryName != null && !p_serialize_1_.entryName.startsWith("custom#"))
        jsonobject.addProperty("entryName", p_serialize_1_.entryName);
    jsonobject.addProperty("weight", (Number)Integer.valueOf(p_serialize_1_.weight));
    jsonobject.addProperty("quality", (Number)Integer.valueOf(p_serialize_1_.quality));

    if (p_serialize_1_.conditions.length > 0)
    {
        jsonobject.add("conditions", p_serialize_3_.serialize(p_serialize_1_.conditions));
    }

    String type = net.minecraftforge.common.ForgeHooks.getLootEntryType(p_serialize_1_);
    if (type != null) jsonobject.addProperty("type", type);
    else
    if (p_serialize_1_ instanceof LootEntryItem)
    {
        jsonobject.addProperty("type", "item");
    }
    else if (p_serialize_1_ instanceof LootEntryTable)
    {
        jsonobject.addProperty("type", "item");
    }
    else
    {
        if (!(p_serialize_1_ instanceof LootEntryEmpty))
        {
            throw new IllegalArgumentException("Don\'t know how to serialize " + p_serialize_1_);
        }

        jsonobject.addProperty("type", "empty");
    }

    p_serialize_1_.serialize(jsonobject, p_serialize_3_);
    return jsonobject;
}
 
Example 58
Project: logistimo-web-service   File: GsonUtil.java   Source Code and License 5 votes vote down vote up
public static String aggTransDataOutputToJson(boolean status, int resultsSize,
                                              List transDataVector, String errMsg, String locale,
                                              String version) {
  Gson
      gson =
      new GsonBuilder().setDateFormat(Constants.DATE_FORMAT)
          .excludeFieldsWithoutExposeAnnotation().create();
  String jsonString = null;
  JsonObject jsonObject = new JsonObject();
  String statusCode = status ? "0" : "1";
  jsonObject.addProperty(JsonTagsZ.VERSION, version);
  jsonObject.addProperty(JsonTagsZ.STATUS, statusCode);
  if (status) {
    jsonObject.addProperty(JsonTagsZ.NUM_RESULTS, resultsSize);
    if (transDataVector != null && !transDataVector.isEmpty()) {
      String transString = gson.toJson(transDataVector);
      JsonElement mElement = gson.fromJson(transString, JsonElement.class);
      jsonObject.add(JsonTagsZ.DATA, mElement);
    }

  } else {
    if (errMsg != null) {
      jsonObject.addProperty(JsonTagsZ.MESSAGE, errMsg);
    }
  }
  if (jsonObject != null) {
    jsonString = gson.toJson(jsonObject);
  }
  return jsonString;
}
 
Example 59
Project: li-android-sdk-core   File: LiBaseResponse.java   Source Code and License 5 votes vote down vote up
private List<LiBaseModel> singleEntityOrListFromJson(final JsonElement node, final String objectNamePlural,
                                                     final String objectName, final Class<? extends LiBaseModel> baseModelClass, final Gson gson) throws LiRestResponseException {
    if (node != null && node.getAsJsonObject().has(DATA)) {
        JsonObject response = node.getAsJsonObject().get(DATA).getAsJsonObject();
        if (!response.has(TYPE)) {
            throw LiRestResponseException.jsonSerializationError("Required data type not found in response");
        }

        String type = response.get(TYPE).getAsString();
        if (!type.equalsIgnoreCase(objectName) && !type.equalsIgnoreCase(objectNamePlural)) {
            throw LiRestResponseException.illegalArgumentError("Required object type not found in response");
        }

        if (type.equalsIgnoreCase(objectNamePlural) && response.get(ITEMS).isJsonArray()) {
            JsonArray jsonArray = response.get(ITEMS).getAsJsonArray();
            List<LiBaseModel> elementList = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JsonObject element = jsonArray.get(i).getAsJsonObject();
                try {
                    elementList.add(gson.fromJson(element, baseModelClass));
                } catch (IllegalStateException | JsonSyntaxException exception) {
                    throw LiRestResponseException.jsonSerializationError("Bad json response:" + exception.getMessage());
                }
            }
            return elementList;
        } else if (type.equalsIgnoreCase(objectName) && response.get(ITEM).isJsonObject()) {
            final List<LiBaseModel> objects = new ArrayList<>();
            objects.add(gson.fromJson(response.get(ITEM).getAsJsonObject(), baseModelClass));
            return objects;
        } else {
            throw LiRestResponseException.jsonSerializationError("Unable to parse " + objectName + " or " +
                    objectNamePlural + " from json:" + node);
        }
    } else {
        throw LiRestResponseException.jsonSerializationError("Server Error. Please check logs");
    }
}
 
Example 60
Project: app-ms   File: GsonMessageBodyHandler.java   Source Code and License 5 votes vote down vote up
@Override
public void writeTo(final JsonElement t,
    final Class<?> type,
    final Type genericType,
    final Annotation[] annotations,
    final MediaType mediaType,
    final MultivaluedMap<String, Object> httpHeaders,
    final OutputStream entityStream) throws IOException {

    try (final OutputStreamWriter w = new OutputStreamWriter(entityStream)) {
        gson.toJson(t, new JsonWriter(w));
    }

}