Java Examples for com.google.gson.JsonElement

The following java examples will help you to understand the usage of com.google.gson.JsonElement. These source code samples are taken from different open source projects.

Example 1
Project: Projectile-master  File: JsonElementListener.java View source code
@Override
public JsonElement responseParser(NetworkResponse networkResponse) {
    String response;
    try {
        response = new String(networkResponse.data, HttpHeaderParser.parseCharset(networkResponse.headers));
    } catch (UnsupportedEncodingException e) {
        response = new String(networkResponse.data);
    }
    return new JsonParser().parse(response);
}
Example 2
Project: bennu-master  File: UserAdapter.java View source code
@Override
public User create(JsonElement jsonElement, JsonBuilder ctx) {
    JsonObject jsonObject = jsonElement.getAsJsonObject();
    final String name = jsonObject.get("name").getAsString();
    final String password = jsonObject.get("password").getAsString();
    final String number = jsonObject.get("number").getAsString();
    return new User(name, password, number);
}
Example 3
Project: jena-sparql-api-master  File: JsonVisitorRewriteSparqlService.java View source code
@Override
public JsonElement visit(JsonObject json) {
    JsonElement result;
    if (json.has("$sparqlService")) {
        JsonArray arr = json.get("$sparqlService").getAsJsonArray();
        JsonObject o = new JsonObject();
        o.addProperty("type", "org.aksw.jena_sparql_api.batch.step.FactoryBeanSparqlService");
        o.add("service", JsonUtils.safeGet(arr, 0));
        o.add("dataset", JsonUtils.safeGet(arr, 1));
        o.add("auth", JsonUtils.safeGet(arr, 2));
        result = o;
    } else {
        result = json;
    }
    return result;
}
Example 4
Project: kurve-server-master  File: SnakeUpdateMessageSerializer.java View source code
public JsonElement serialize(SnakeUpdateMessage src, Type typeOfSrc, JsonSerializationContext context) {
    if (src.getJsonElement() == null) {
        JsonObject responseObject = new JsonObject();
        responseObject.addProperty("code", GameWebSocketHandler.MessageType.CODE_SNAKE_ARC_RESPONSE.ordinal());
        responseObject.add("snake", context.serialize(src.getSnake()));
        responseObject.addProperty("id", src.getId());
        src.setJsonElement(responseObject);
    }
    return src.getJsonElement();
}
Example 5
Project: tabula-java-master  File: TableSerializer.java View source code
@Override
public JsonElement serialize(Table table, Type type, JsonSerializationContext context) {
    JsonObject object = new JsonObject();
    if (table.getExtractionAlgorithm() == null) {
        object.addProperty("extraction_method", "");
    } else {
        object.addProperty("extraction_method", (table.getExtractionAlgorithm()).toString());
    }
    object.addProperty("top", table.getTop());
    object.addProperty("left", table.getLeft());
    object.addProperty("width", table.getWidth());
    object.addProperty("height", table.getHeight());
    JsonArray jsonDataArray = new JsonArray();
    for (List<RectangularTextContainer> row : table.getRows()) {
        JsonArray jsonRowArray = new JsonArray();
        for (RectangularTextContainer textChunk : row) {
            jsonRowArray.add(context.serialize(textChunk));
        }
        jsonDataArray.add(jsonRowArray);
    }
    object.add("data", jsonDataArray);
    return object;
}
Example 6
Project: ulti-master  File: JsonUtil.java View source code
public static ArrayList getArrayListMapFromJson(String jsonString) {
    JsonParser jsonParser = new JsonParser();
    Gson gson = new Gson();
    JsonElement jsonElement = jsonParser.parse(jsonString);
    Logs.d(jsonElement.isJsonArray() + "   " + jsonElement.isJsonObject());
    ArrayList<HashMap<String, Object>> arrayList = new ArrayList<HashMap<String, Object>>();
    if (jsonElement.isJsonObject()) {
        arrayList.add(gson.fromJson(jsonElement, HashMap.class));
    } else if (jsonElement.isJsonArray()) {
        arrayList = getListFromJson(jsonString, new TypeToken<ArrayList<HashMap<String, Object>>>() {
        });
    }
    return arrayList;
}
Example 7
Project: UltimateAndroid-master  File: JsonUtil.java View source code
public static ArrayList getArrayListMapFromJson(String jsonString) {
    JsonParser jsonParser = new JsonParser();
    Gson gson = new Gson();
    JsonElement jsonElement = jsonParser.parse(jsonString);
    Logs.d(jsonElement.isJsonArray() + "   " + jsonElement.isJsonObject());
    ArrayList<HashMap<String, Object>> arrayList = new ArrayList<HashMap<String, Object>>();
    if (jsonElement.isJsonObject()) {
        arrayList.add(gson.fromJson(jsonElement, HashMap.class));
    } else if (jsonElement.isJsonArray()) {
        arrayList = getListFromJson(jsonString, new TypeToken<ArrayList<HashMap<String, Object>>>() {
        });
    }
    return arrayList;
}
Example 8
Project: android_xcore-master  File: GsonPrimitiveJoinerConverter.java View source code
@Override
public void convert(Params params) {
    StringBuilder tagsBuilder = new StringBuilder();
    JsonArray jsonArray = params.getJsonArray();
    for (int i = 0; i < jsonArray.size(); i++) {
        JsonElement item = jsonArray.get(i);
        tagsBuilder.append(item.getAsString());
        if (i != jsonArray.size() - 1) {
            tagsBuilder.append(getSplitter());
        }
    }
    String result = tagsBuilder.toString();
    Log.xd(this, "tagsJsonConverter " + result);
    if (!StringUtil.isEmpty(result)) {
        params.getContentValues().put(getEntityKey(), result);
    }
}
Example 9
Project: ApprovalTests.Java-master  File: JsonUtils.java View source code
public static String prettyPrint(String json) {
    if (!ObjectUtils.isClassPresent("com.google.gson.Gson")) {
        throw new RuntimeException("Missing Gson dependency\n  Pretty print uses Gson parser.\n  You can get this from the maven repo \n  or https://github.com/google/gson");
    }
    try {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        JsonParser jp = new JsonParser();
        JsonElement je = jp.parse(json);
        return gson.toJson(je);
    } catch (JsonSyntaxException e) {
        return String.format("Error:%s\nJson:\n%s", e.getMessage(), json);
    }
}
Example 10
Project: bonaparte-java-master  File: GsonObjectAdapter.java View source code
public static <E extends Exception> JsonObject unmarshal(String str, ExceptionConverter<E> p) throws E {
    if (str == null)
        return null;
    try {
        JsonElement elem = new JsonParser().parse(str);
        if (elem instanceof JsonObject)
            return (JsonObject) elem;
        throw new Exception("Parsed JSON is not an object");
    } catch (Exception e) {
        throw p.customExceptionConverter("cannot parse JSON object", e);
    }
}
Example 11
Project: buckaroo-master  File: RecipeVersionSerializer.java View source code
@Override
public JsonElement serialize(final RecipeVersion recipeVersion, final Type type, final JsonSerializationContext context) {
    Preconditions.checkNotNull(recipeVersion);
    Preconditions.checkNotNull(type);
    Preconditions.checkNotNull(context);
    final JsonObject jsonObject = new JsonObject();
    final JsonElement sourceElement = Either.join(recipeVersion.source, context::serialize, context::serialize);
    jsonObject.add("source", sourceElement);
    if (recipeVersion.target.isPresent()) {
        jsonObject.addProperty("target", recipeVersion.target.get());
    }
    if (!recipeVersion.dependencies.isEmpty()) {
        jsonObject.add("dependencies", context.serialize(recipeVersion.dependencies));
    }
    if (recipeVersion.buckResource.isPresent()) {
        jsonObject.add("buck", context.serialize(recipeVersion.buckResource.get(), RemoteFile.class));
    }
    return jsonObject;
}
Example 12
Project: Buddy-Android-SDK-master  File: BuddyLocationDeserializer.java View source code
@Override
public Location deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) throws JsonParseException {
    JsonObject jsonObj = json.getAsJsonObject();
    if (jsonObj != null && jsonObj.has("lat") && jsonObj.has("lng")) {
        Location l = new Location("Buddy");
        l.setLatitude(jsonObj.get("lat").getAsDouble());
        l.setLongitude(jsonObj.get("lng").getAsDouble());
        return l;
    }
    throw new JsonParseException("Invalid location: " + json.toString());
}
Example 13
Project: Cardinal-Plus-master  File: GitUtils.java View source code
public static String getLatestGitRevision() {
    try {
        JsonParser parser = new JsonParser();
        JsonElement jsonElement = parser.parse(new InputStreamReader(new URL("https://api.github.com/repos/twizmwazin/CardinalPGM/git/refs/heads/master").openStream()));
        return jsonElement.getAsJsonObject().getAsJsonObject("object").get("sha").getAsString();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
Example 14
Project: CardinalPGM-master  File: GitUtil.java View source code
public static String getLatestGitRevision() {
    try {
        JsonParser parser = new JsonParser();
        JsonElement jsonElement = parser.parse(new InputStreamReader(new URL("https://api.github.com/repos/twizmwazin/CardinalPGM/git/refs/heads/master").openStream()));
        return jsonElement.getAsJsonObject().getAsJsonObject("object").get("sha").getAsString();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
Example 15
Project: DeviveWallSuite-master  File: GameControlDeserializer.java View source code
@Override
public Protocol deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
    Protocol protocol = protocolDeserializer.deserialize(json, typeOfT, context);
    if (protocol == null) {
        return null;
    }
    final GameControlMessageType messageType = GameControlMessageType.getModelType(protocol.getType());
    final JsonElement dataJsonElement = json.getAsJsonObject().get(Protocol.DATA);
    if (dataJsonElement == null)
        return null;
    Data data = null;
    switch(messageType) {
        case CLIENT_START:
            data = context.deserialize(dataJsonElement, ClientStartRequest.class);
            break;
        case SERVER_START:
            data = context.deserialize(dataJsonElement, ServerStartResponse.class);
            break;
        default:
            break;
    }
    protocol = new Protocol(protocol.getId(), protocol.getType(), data);
    return protocol;
}
Example 16
Project: Dynmap-Multiserver-master  File: ComponentDeserializer.java View source code
@Override
public Component deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    JsonObject jsonObject = jsonElement.getAsJsonObject();
    for (Component component : components) {
        if (component.isComponent(jsonObject)) {
            Component component1 = new Gson().fromJson(jsonElement, component.getClass());
            return component1;
        }
    }
    return null;
}
Example 17
Project: eGov-master  File: BudgetGroupJsonAdaptor.java View source code
@Override
public JsonElement serialize(final BudgetGroup budgetGroup, final Type type, final JsonSerializationContext jsc) {
    final JsonObject jsonObject = new JsonObject();
    if (budgetGroup != null) {
        if (budgetGroup.getName() != null)
            jsonObject.addProperty("name", budgetGroup.getName());
        else
            jsonObject.addProperty("name", "");
        if (budgetGroup.getMajorCode() != null)
            jsonObject.addProperty("majorCode", budgetGroup.getMajorCode().getName());
        else
            jsonObject.addProperty("majorCode", "");
        if (budgetGroup.getMaxCode() != null)
            jsonObject.addProperty("maxCode", budgetGroup.getMaxCode().getName());
        else
            jsonObject.addProperty("maxCode", "");
        if (budgetGroup.getMinCode() != null)
            jsonObject.addProperty("minCode", budgetGroup.getMinCode().getName());
        else
            jsonObject.addProperty("minCode", "");
        if (budgetGroup.getAccountType() != null)
            jsonObject.addProperty("accountType", budgetGroup.getAccountType().toString());
        else
            jsonObject.addProperty("accountType", "");
        if (budgetGroup.getBudgetingType() != null)
            jsonObject.addProperty("budgetingType", budgetGroup.getBudgetingType().toString());
        else
            jsonObject.addProperty("budgetingType", "");
        jsonObject.addProperty("isActive", Boolean.toString(budgetGroup.getIsActive()).toUpperCase());
        jsonObject.addProperty("id", budgetGroup.getId());
    }
    return jsonObject;
}
Example 18
Project: Enrichr-master  File: ListAdapter.java View source code
@Override
public JsonElement serialize(List list, Type type, JsonSerializationContext jsc) {
    JsonObject jsonObject = new JsonObject();
    // Don't show int count, show encoded version instead
    jsonObject.addProperty("list_id", Shortener.encode(list.getListid()));
    jsonObject.addProperty("description", list.getDescription());
    jsonObject.addProperty("passkey", list.getPasskey());
    jsonObject.add("created", jsc.serialize(list.getCreated()));
    return jsonObject;
}
Example 19
Project: fenixedu-academic-master  File: StudentStatuteJsonAdapter.java View source code
@Override
public JsonElement view(StudentStatute studentStatute, JsonBuilder ctx) {
    JsonObject statuteType = new JsonObject();
    statuteType.addProperty("id", studentStatute.getType().getExternalId());
    statuteType.addProperty("name", studentStatute.getType().getName().getContent());
    JsonObject object = new JsonObject();
    object.add("type", statuteType);
    object.addProperty("comment", studentStatute.getComment());
    return object;
}
Example 20
Project: fluxtream-app-master  File: DateDeserializer.java View source code
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    if (json.isJsonObject()) {
        final JsonObject asJsonObject = json.getAsJsonObject();
        final JsonElement iso = asJsonObject.get("iso");
        final String asString = iso.getAsString();
        final Calendar calendar = DatatypeConverter.parseDateTime(asString);
        return calendar.getTime();
    } else {
        final String asString = json.getAsString();
        final Calendar calendar = DatatypeConverter.parseDateTime(asString);
        return calendar.getTime();
    }
}
Example 21
Project: futuristic-master  File: JsonHttpClient.java View source code
@Override
protected JsonElement responseToObject(HttpResponse<InputStream> response) {
    JsonParser parser = new JsonParser();
    JsonElement obj = null;
    try {
        if (response.getBody() != null) {
            InputStreamReader requestBody = new InputStreamReader(response.getBody());
            obj = parser.parse(requestBody);
        }
    } catch (JsonSyntaxException ex) {
        if (response.getStatusCode() == 200) {
            throw ex;
        }
    }
    return obj;
}
Example 22
Project: gdl-tools-master  File: ArchetypeReferenceJsonSerializer.java View source code
@Override
public ArchetypeReference deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    ArchetypeReference archetypeReference = gson.fromJson(json, ArchetypeReference.class);
    for (ElementInstance elementInstance : archetypeReference.getElementInstancesMap().values()) {
        elementInstance.setArchetypeReference(archetypeReference);
    }
    return archetypeReference;
}
Example 23
Project: gerrit-rest-java-client-master  File: CommitInfoParserTest.java View source code
@Test
public void testParseCommitInfo() throws Exception {
    JsonElement jsonElement = getJsonElement("commit.json");
    List<CommitInfo> commitInfos = commitInfoParser.parseCommitInfos(jsonElement);
    Truth.assertThat(commitInfos).hasSize(1);
    Truth.assertThat(commitInfos.get(0).message.equals("Use an EventBus to manage star icons  Image widgets that need to ..."));
}
Example 24
Project: github-analysis-master  File: ActorDeserializer.java View source code
public Actor deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    Actor actor = new Actor();
    if (json.isJsonPrimitive()) {
        actor.login = json.getAsJsonPrimitive().getAsString();
    } else {
        JsonObject jsObj = json.getAsJsonObject();
        JsonElement login = jsObj.get("login");
        if (login != null) {
            actor.login = login.getAsString();
        }
    }
    return actor;
}
Example 25
Project: ha-bridge-master  File: ServiceDeserializer.java View source code
@Override
public Service deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) {
    JsonObject objServices = json.getAsJsonObject();
    String theKey;
    domain = objServices.get("domain").getAsString();
    JsonObject obj = objServices.get("services").getAsJsonObject();
    services = new HashMap<String, ServiceElement>();
    for (Entry<String, JsonElement> entry : obj.entrySet()) {
        ServiceElement theServiceElement = new ServiceElement();
        theKey = entry.getKey();
        JsonObject theRawDetail = obj.getAsJsonObject(theKey);
        theServiceElement.setDescription(theRawDetail.get("description").getAsString());
        theServiceElement.setField(ctx.deserialize(theRawDetail.get("fields"), Field.class));
        services.put(theKey, theServiceElement);
    }
    return new Service(domain, services);
}
Example 26
Project: Hirebird-master  File: JsonUtils.java View source code
public static <T> T readModel(Context context, String fileName, String xpath, Class<T> clazz) {
    InputStream is = null;
    try {
        is = context.getAssets().open(fileName);
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        String bufferString = new String(buffer);
        JsonParser parser = new JsonParser();
        JsonElement json = parser.parse(bufferString);
        return gson.fromJson(json.getAsJsonObject().get(xpath), clazz);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
Example 27
Project: iis-master  File: DurationReportValueJsonConverterTest.java View source code
@Test
public void convertValue() {
    // given
    ReportEntry reportEntry = new ReportEntry("report.key", ReportEntryType.DURATION, "3842000");
    // execute
    JsonElement json = converter.convertValue(reportEntry);
    // assert
    JsonElement expectedJson = new JsonParser().parse("{milliseconds: 3842000, humanReadable: \"1h 04m 02s\"}");
    assertEquals(expectedJson, json);
}
Example 28
Project: maketaobao-master  File: HttpObjectDeserializer.java View source code
@Override
public HttpObject deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    final HttpObject httpObject = new HttpObject();
    final JsonObject jsonObject = jsonElement.getAsJsonObject();
    httpObject.setCode(jsonObject.get("code").getAsInt());
    httpObject.setCodeMsg(jsonObject.get("codeMsg").getAsString());
    httpObject.setData(jsonObject.get("data").getAsJsonArray());
    return httpObject;
}
Example 29
Project: minecraft-roguelike-master  File: BlockProvider.java View source code
public static IBlockFactory create(JsonObject block) throws Exception {
    BlockProvider type;
    if (block.has("type")) {
        String t = block.get("type").getAsString();
        type = BlockProvider.valueOf(t);
    } else {
        type = METABLOCK;
    }
    JsonElement data;
    if (block.has("data")) {
        data = block.get("data");
    } else {
        data = block;
    }
    switch(type) {
        case METABLOCK:
            return new MetaBlock(data);
        case WEIGHTED:
            return new BlockWeightedRandom(data);
        case CHECKERS:
            return new BlockCheckers(data);
        case JUMBLE:
            return new BlockJumble(data);
        case STRIPES:
            return new BlockStripes(data);
        case LAYERS:
            return new BlockLayers(data);
        case COLUMNS:
            return new BlockColumns(data);
        default:
            return null;
    }
}
Example 30
Project: MinecraftNetLib-master  File: TranslationMessage.java View source code
@Override
public JsonElement toJson() {
    JsonElement jsonElement = super.toJson();
    if (jsonElement.isJsonObject()) {
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        jsonObject.addProperty("translate", this.translateKey);
        JsonArray array = new JsonArray();
        for (Message message : this.translationParts) {
            array.add(message.toJson());
        }
        jsonObject.add("with", array);
        return jsonObject;
    }
    return jsonElement;
}
Example 31
Project: olca-modules-master  File: NwSets.java View source code
static NwSet map(JsonObject json, List<ImpactCategory> categories) {
    if (json == null)
        return null;
    NwSet set = new NwSet();
    In.mapAtts(json, set, 0);
    set.setWeightedScoreUnit(In.getString(json, "weightedScoreUnit"));
    JsonArray factors = In.getArray(json, "factors");
    if (factors == null)
        return set;
    for (JsonElement f : factors) {
        if (!f.isJsonObject())
            continue;
        NwFactor factor = mapFactor(f.getAsJsonObject(), categories);
        set.getFactors().add(factor);
    }
    return set;
}
Example 32
Project: pay-master  File: TradeInfoAdapter.java View source code
public JsonElement serialize(List<TradeInfo> tradeInfoList, Type type, JsonSerializationContext jsonSerializationContext) {
    if (Utils.isListEmpty(tradeInfoList)) {
        return null;
    }
    TradeInfo tradeInfo = (TradeInfo) tradeInfoList.get(0);
    if ((tradeInfo instanceof PosTradeInfo)) {
        return new JsonPrimitive(StringUtils.join(tradeInfoList, ""));
    }
    return jsonSerializationContext.serialize(tradeInfoList);
}
Example 33
Project: ps-framework-master  File: ServiceExceptionSerializer.java View source code
public JsonElement serialize(ServiceException src, Type typeOfSrc, JsonSerializationContext context) {
    // create root
    JsonObject root = new JsonObject();
    // create exception
    JsonObject exception = new JsonObject();
    root.add("ServiceException", exception);
    // add messages
    exception.add("message", new JsonPrimitive(src.getMessage()));
    exception.add("detail", new JsonPrimitive(src.getDetail()));
    return root;
}
Example 34
Project: Quadrum-2-master  File: JsonVerification.java View source code
public static boolean verifyRequirements(File file, JsonObject jsonObject, Class<?> clazz) {
    List<String> keys = Lists.newArrayList();
    for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) keys.add(entry.getKey());
    List<String> missingFields = Lists.newArrayList();
    for (Field field : clazz.getDeclaredFields()) {
        String name = field.getName();
        if (field.getAnnotation(SerializedName.class) != null)
            name = field.getAnnotation(SerializedName.class).value();
        if (field.getAnnotation(Required.class) != null && !keys.contains(name))
            missingFields.add(name);
    }
    if (!missingFields.isEmpty()) {
        Quadrum.log(Level.WARN, ERROR, file.getName(), missingFields);
        return false;
    } else
        return true;
}
Example 35
Project: Quadrum-master  File: JsonVerification.java View source code
public static boolean verifyRequirements(File file, JsonObject jsonObject, Class<?> clazz) {
    List<String> keys = Lists.newArrayList();
    for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
        keys.add(entry.getKey());
    }
    List<String> missingFields = Lists.newArrayList();
    for (Field field : clazz.getDeclaredFields()) {
        String name = field.getName();
        if (field.getAnnotation(SerializedName.class) != null) {
            name = field.getAnnotation(SerializedName.class).value();
        }
        if (field.getAnnotation(Required.class) != null && !keys.contains(name)) {
            missingFields.add(name);
        }
    }
    if (!missingFields.isEmpty()) {
        Quadrum.log(Level.WARN, ERROR, file.getName(), missingFields);
        return false;
    } else {
        return true;
    }
}
Example 36
Project: slack4gerrit-master  File: CherryPicksHelper.java View source code
static String getCherryPickLegacyId(String cherryPickRequestJSONResponse) {
    LOGGER.debug("parsing Cherry pick request : " + cherryPickRequestJSONResponse);
    cherryPickRequestJSONResponse = cherryPickRequestJSONResponse.substring(4);
    JsonParser parser = new JsonParser();
    long lowestLegacyId = Long.MAX_VALUE;
    JsonArray obj = parser.parse(cherryPickRequestJSONResponse).getAsJsonArray();
    for (JsonElement jsonElement : obj) {
        JsonObject jsonChange = jsonElement.getAsJsonObject();
        long cherryPickLegacyId = GsonHelper.getLongOrNull(jsonChange.get("_number"));
        if (cherryPickLegacyId < lowestLegacyId) {
            lowestLegacyId = cherryPickLegacyId;
        }
    }
    return Long.toString(lowestLegacyId);
}
Example 37
Project: SlipStreamServer-master  File: UsageSummary.java View source code
protected Map<String, Double> getMetrics() {
    Map<String, Double> result = new HashMap<String, Double>();
    for (Map.Entry<String, JsonElement> entry : usage.getAsJsonObject().entrySet()) {
        String metricName = entry.getKey();
        Double metricValue = entry.getValue().getAsJsonObject().get("unit-minutes").getAsDouble();
        result.put(metricName, metricValue);
    }
    return result;
}
Example 38
Project: smtp-sender-master  File: PartDataJsonDeserializer.java View source code
@Override
public PartData deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    String contentTypeStr = json.getAsJsonObject().get("contentType").getAsString();
    ContentType contentType = ContentType.valueOf(contentTypeStr);
    Gson gson = new GsonBuilder().registerTypeAdapter(PartData.class, new PartDataJsonDeserializer()).create();
    return gson.fromJson(json, contentType.getDataClass());
}
Example 39
Project: soundmap-master  File: GeoLocationDeserializer.java View source code
@Override
public GeoLocation deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    String text = json.getAsString().trim();
    // Format example: "41.0082325664 28.9731252193"
    String[] latLong = text.split(" ", 2);
    if (latLong.length != 2) {
        throw new JsonParseException(String.format("Unable to deserialize latitude/long values from: %s", text));
    }
    return new GeoLocation(Double.valueOf((latLong[0])), Double.valueOf((latLong[1])));
}
Example 40
Project: TflTravelAlerts-master  File: SparseArraySerializer.java View source code
@Override
public JsonElement serialize(SparseArray<?> src, Type typeOfSrc, JsonSerializationContext context) {
    int size = src.size();
    int[] keys = new int[size];
    Object[] values = new Object[size];
    for (int i = 0; i < size; i++) {
        keys[i] = src.keyAt(i);
        values[i] = src.valueAt(i);
    }
    JsonObject root = new JsonObject();
    root.add("keys", context.serialize(keys));
    root.add("values", context.serialize(values));
    return root;
}
Example 41
Project: the-blue-alliance-android-master  File: TeamStatsExtractorTest.java View source code
@Test
public void testTeamStatsExtractor() {
    JsonElement stats = mExtractor.call(mAllStats);
    assertNotNull(stats);
    assertTrue(stats.isJsonObject());
    JsonObject statsObject = stats.getAsJsonObject();
    assertTrue(statsObject.has("opr"));
    assertTrue(statsObject.has("dpr"));
    assertTrue(statsObject.has("ccwm"));
    assertEquals(statsObject.get("opr").getAsDouble(), 87.957372917501459, .01);
    assertEquals(statsObject.get("dpr").getAsDouble(), 50.887943082425011, .01);
    assertEquals(statsObject.get("ccwm").getAsDouble(), 37.06942983507642, .01);
}
Example 42
Project: vraptor-master  File: MessageSerializerTest.java View source code
@Test
public void shouldSerializeI18nMessage() {
    String expectedResult = "{\"category\":\"validation\",\"message\":\"you are underage\"}";
    I18nMessage message = new I18nMessage("validation", "underage");
    message.setBundle(ResourceBundle.getBundle("messages"));
    JsonElement jsonElement = new MessageSerializer().serialize(message, mock(Type.class), mock(JsonSerializationContext.class));
    assertEquals(expectedResult, jsonElement.getAsJsonObject().toString());
}
Example 43
Project: wikibrain-master  File: TestWikidataValue.java View source code
@Test
public void testSerializable() throws IOException, ClassNotFoundException {
    Object value = Arrays.asList("Foo", "bar", "baz");
    JsonElement json = new JsonParser().parse("['Foo', 'bar', 'baz']");
    WikidataValue wdVal = new WikidataValue("atype", value, json);
    byte[] bytes = WpIOUtils.objectToBytes(wdVal);
    WikidataValue wdVal2 = (WikidataValue) WpIOUtils.bytesToObject(bytes);
    byte[] bytes2 = WpIOUtils.objectToBytes(wdVal2);
    assertEquals(bytes.length, bytes2.length);
    for (int i = 0; i < bytes.length; i++) {
        assertEquals(bytes[i], bytes2[i]);
    }
}
Example 44
Project: YourAppIdea-master  File: LocationDeserializer.java View source code
@Override
public Location deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    JsonObject jsonObject = jsonElement.getAsJsonObject();
    Location location = new Location("mongodb");
    JsonArray coord = jsonObject.getAsJsonArray("coordinates");
    location.setLongitude(coord.get(0).getAsDouble());
    location.setLatitude(coord.get(1).getAsDouble());
    return location;
}
Example 45
Project: Youtube-Hacked-Client-1.8-master  File: PlayerConfigurationReceiver.java View source code
public void fileDownloadFinished(String url, byte[] bytes, Throwable exception) {
    if (bytes != null) {
        try {
            String e = new String(bytes, "ASCII");
            JsonParser jp = new JsonParser();
            JsonElement je = jp.parse(e);
            PlayerConfigurationParser pcp = new PlayerConfigurationParser(this.player);
            PlayerConfiguration pc = pcp.parsePlayerConfiguration(je);
            if (pc != null) {
                pc.setInitialized(true);
                PlayerConfigurations.setPlayerConfiguration(this.player, pc);
            }
        } catch (Exception var9) {
            var9.printStackTrace();
        }
    }
}
Example 46
Project: sosies-generator-master  File: JsonTreeTest.java View source code
@Test(timeout = 1000)
public void testToJsonTree_add1192() {
    fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(), this, "testToJsonTree_add1192");
    TestTypes.BagOfPrimitives bag = new TestTypes.BagOfPrimitives(10L, 5, false, "foo");
    JsonElement json = gson.toJsonTree(bag);
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 1719, json, 1718, json.isJsonObject());
    JsonObject obj = json.getAsJsonObject();
    Set<java.util.Map.Entry<java.lang.String, com.google.gson.JsonElement>> children = obj.entrySet();
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 1721, children, 1720, children.size());
    assertContains(obj, new JsonPrimitive(10L));
    assertContains(obj, new JsonPrimitive(10L));
    assertContains(obj, new JsonPrimitive(5));
    assertContains(obj, new JsonPrimitive(false));
    assertContains(obj, new JsonPrimitive("foo"));
    fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread());
}
Example 47
Project: Tinman-master  File: XapiStatementResultJson.java View source code
/* (non-Javadoc)
	 * @see com.google.gson.JsonSerializer#serialize(java.lang.Object, java.lang.reflect.Type, com.google.gson.JsonSerializationContext)
	 */
@Override
public JsonElement serialize(XapiStatementResult arg0, Type arg1, JsonSerializationContext arg2) {
    JsonObject result = new JsonObject();
    if (arg0.hasStatements()) {
        result.add("statements", arg2.serialize(arg0.getStatements(), XapiStatementBatch.class));
    }
    if (arg0.hasMore()) {
        result.addProperty("more", arg0.getMore().toString());
    }
    return result;
}
Example 48
Project: android-http-lib-based-on-volley-master  File: JsonStreamParser.java View source code
/**
   * Returns the next available {@link com.google.gson.JsonElement} on the reader. Null if none available.
   * 
   * @return the next available {@link com.google.gson.JsonElement} on the reader. Null if none available.
   * @throws JsonParseException if the incoming stream is malformed JSON.
   * @since 1.4
   */
public JsonElement next() throws JsonParseException {
    if (!hasNext()) {
        throw new NoSuchElementException();
    }
    try {
        return Streams.parse(parser);
    } catch (StackOverflowError e) {
        throw new JsonParseException("Failed parsing JSON source to Json", e);
    } catch (OutOfMemoryError e) {
        throw new JsonParseException("Failed parsing JSON source to Json", e);
    } catch (JsonParseException e) {
        throw e.getCause() instanceof EOFException ? new NoSuchElementException() : e;
    }
}
Example 49
Project: activitystreams-master  File: ParametersAdapter.java View source code
@Override
public ParametersValue deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
    checkArgument(json.isJsonObject());
    JsonObject obj = json.getAsJsonObject();
    ParametersValue.Builder builder = ParametersValue.make();
    for (Map.Entry<String, JsonElement> entry : obj.entrySet()) builder.param(entry.getKey(), context.<ParameterValue>deserialize(entry.getValue(), ParameterValue.class));
    return builder.get();
}
Example 50
Project: ARKCraft-Code-master  File: PageDeserializer.java View source code
@Override
public Page deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
    JsonObject jObject = json.getAsJsonObject();
    try {
        LogHelper.info("Deserializing Objects! PageDeserializer.deserialize() called!");
        Class<? extends Page> pageClass = PageData.getPageClass(jObject.get("type").getAsString());
        LogHelper.info("Reached after pageClass.");
        LogHelper.info(jObject.get("type") == null ? "JObject is null!" : "JObject is not null.");
        LogHelper.info(pageClass == null ? "Page Class is null!" : "Page class is not null.");
        return context.deserialize(jObject, pageClass);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Example 51
Project: AsyncHttpClient-master  File: SyncPutTest.java View source code
/**
	 * Tests response parses correctly from json
	 */
public void testPutJson() {
    RequestBody putBody = RequestBody.create(MediaType.parse("application/json"), "{\"test\":\"hello world\"}");
    SyncHttpClient<JsonElement> client = new SyncHttpClient<>("http://httpbin.org/");
    JsonElement response = client.put("put", putBody, new JsonResponseHandler());
    Assert.assertNotNull(response);
}
Example 52
Project: Avengers-master  File: MarvelResultsComicsDeserialiser.java View source code
@Override
public List<Comic> deserialize(JsonElement je, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    Type listType = new TypeToken<List<Comic>>() {
    }.getType();
    JsonElement data = je.getAsJsonObject().get("data");
    JsonElement results = je.getAsJsonObject().get("results");
    JsonArray resultsArray = results.getAsJsonArray();
    JsonElement comicsObject = resultsArray.get(0);
    JsonElement items = comicsObject.getAsJsonObject().get("items");
    return new Gson().fromJson(items, listType);
}
Example 53
Project: BiliNyan-Android-master  File: List.java View source code
public static List createFromJson(String json) {
    List result = new Gson().fromJson(json, List.class);
    Iterator<Map.Entry<String, JsonElement>> iterator = result.list.entrySet().iterator();
    if (result.lists == null) {
        result.lists = new ArrayList<>();
    }
    while (iterator.hasNext()) {
        Map.Entry<String, JsonElement> element = iterator.next();
        try {
            result.lists.add(new Gson().fromJson(element.getValue(), VideoItemInfo.class));
        } catch (Exception e) {
        }
    }
    result.list = null;
    return result;
}
Example 54
Project: breakout-master  File: SnakeYaml2Gson.java View source code
public static JsonElement toJsonElement(Object yaml) {
    if (yaml == null) {
        return JsonNull.INSTANCE;
    } else if (yaml instanceof List) {
        return toJsonArray((List<?>) yaml);
    } else if (yaml instanceof Map) {
        return toJsonObject((Map<?, ?>) yaml);
    } else {
        return new JsonPrimitive(yaml.toString());
    }
}
Example 55
Project: BungeeCord-master  File: PlayerInfoSerializer.java View source code
@Override
public ServerPing.PlayerInfo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    JsonObject js = json.getAsJsonObject();
    ServerPing.PlayerInfo info = new ServerPing.PlayerInfo(js.get("name").getAsString(), (UUID) null);
    String id = js.get("id").getAsString();
    if (!id.contains("-")) {
        info.setId(id);
    } else {
        info.setUniqueId(UUID.fromString(id));
    }
    return info;
}
Example 56
Project: collaboro-master  File: LanguagesAvailableServlet.java View source code
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    addResponseOptions(response);
    response.setContentType("application/json");
    PrintWriter out = response.getWriter();
    JsonArray languages = new JsonArray();
    for (String languageName : CollaboroBackendFactory.getActiveLanguages()) {
        JsonElement languageElement = new JsonPrimitive(languageName);
        languages.add(languageElement);
    }
    JsonObject jsonResponse = new JsonObject();
    jsonResponse.add("languages", languages);
    out.print(jsonResponse.toString());
}
Example 57
Project: com.mzeat-master  File: DateTimeTypeAdapter.java View source code
@Override
public java.util.Date deserialize(JsonElement json, Type t, JsonDeserializationContext arg2) throws JsonParseException {
    if (!(json instanceof JsonPrimitive)) {
        throw new JsonParseException("The date should be a string value");
    }
    try {
        Date date = format.parse(json.getAsString());
        return new java.util.Date(date.getTime());
    } catch (ParseException e) {
        throw new JsonParseException(e);
    }
}
Example 58
Project: contentful.java-master  File: ResourceDeserializer.java View source code
@Override
public CDAResource deserialize(JsonElement json, Type classType, JsonDeserializationContext context) throws JsonParseException {
    CDAType cdaType = extractType(json);
    CDAResource result = context.deserialize(json, classForType(cdaType));
    if (ASSET.equals(cdaType) || ENTRY.equals(cdaType)) {
        LocalizedResource localized = (LocalizedResource) result;
        if (localized.fields == null) {
            localized.fields = Collections.emptyMap();
        }
    }
    return result;
}
Example 59
Project: csv2DB-master  File: ValueDefinitionAdapter.java View source code
@Override
public ValueDefinition deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    if (json instanceof JsonPrimitive) {
        JsonPrimitive jsonPrimitive = (JsonPrimitive) json;
        if (jsonPrimitive.isString()) {
            return new StringLiteral(json.getAsString());
        }
        if (jsonPrimitive.isBoolean()) {
            return new BooleanLiteral(json.getAsBoolean());
        }
        if (jsonPrimitive.isNumber()) {
            return new NumberLiteral(json.getAsNumber());
        }
        throw new JsonParseException("Unsupported value definition: " + jsonPrimitive);
    } else {
        JsonObject definition = json.getAsJsonObject();
        if (definition.get("function") != null) {
            return new FunctionReference(definition.get("function").getAsString());
        }
        if (definition.get("sql") != null) {
            return new SqlLiteral(definition.get("sql").getAsString());
        }
        throw new JsonParseException("Unsupported value definition: " + definition);
    }
}
Example 60
Project: dandy-master  File: DrupalFieldAdapter.java View source code
public JsonElement serialize(ArrayList<DrupalField> src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject retVal = new JsonObject();
    for (DrupalField drupalField : src) {
        String name = drupalField.getName();
        JsonObject fieldObject = new JsonObject();
        ArrayList<HashMap<String, String>> values = drupalField.getValues();
        for (int i = 0; i < values.size(); i++) {
            HashMap<String, String> map = values.get(i);
            JsonObject valueObject = new JsonObject();
            for (Map.Entry<String, String> entry : map.entrySet()) {
                valueObject.addProperty(entry.getKey(), entry.getValue());
            }
            fieldObject.add(String.valueOf(i), valueObject);
        }
        retVal.add(name, fieldObject);
    }
    return retVal;
}
Example 61
Project: edx-app-android-master  File: JsonPageDeserializer.java View source code
@Override
public Page<?> deserialize(JsonElement json, final Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    final List<?> list = context.deserialize(json.getAsJsonObject().get("results"), new ParameterizedType() {

        public Type getRawType() {
            return List.class;
        }

        public Type getOwnerType() {
            return null;
        }

        public Type[] getActualTypeArguments() {
            return ((ParameterizedType) typeOfT).getActualTypeArguments();
        }
    });
    JsonElement paginationJson = json.getAsJsonObject().get("pagination");
    if (null == paginationJson || paginationJson.isJsonNull()) {
        paginationJson = json;
    }
    final PaginationData paginationData = context.deserialize(paginationJson, PaginationData.class);
    return new Page<>(paginationData, list);
}
Example 62
Project: ForgeEssentials-master  File: UserIdentType.java View source code
@Override
public UserIdent deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
    if (json.isJsonObject()) {
        JsonObject obj = json.getAsJsonObject();
        JsonElement uuid = obj.get("uuid");
        JsonElement username = obj.get("username");
        if (uuid == null)
            return UserIdent.get(username.getAsString());
        else if (username == null)
            return UserIdent.get(uuid.getAsString());
        else
            return UserIdent.get(uuid.getAsString(), username.getAsString());
    }
    return UserIdent.fromString(json.getAsString());
}
Example 63
Project: Greencode-Framework-master  File: DOMDeserializer.java View source code
public DOM deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
    try {
        DOM d = (DOM) GenericReflection.NoThrow.getDeclaredConstrutor((Class<?>) arg1, Window.class).newInstance(context.currentWindow());
        for (Entry<String, JsonElement> entry : ((JsonObject) arg0).entrySet()) {
            Field f = GenericReflection.NoThrow.getDeclaredField(d.getClass(), entry.getKey());
            f.set(d, arg2.deserialize(entry.getValue(), f.getType()));
        }
        return d;
    } catch (Exception e) {
        throw new JsonParseException(e);
    }
}
Example 64
Project: GSoC-master  File: ValueDeserializer.java View source code
@Override
public Values deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    final Values values = new Values();
    if (json.isJsonArray()) {
        String[] vals = context.deserialize(json, String[].class);
        values.setValues(vals);
    } else if (json.isJsonPrimitive()) {
        values.setIntValue(json.getAsJsonPrimitive().getAsInt());
    }
    return values;
}
Example 65
Project: gson-fire-master  File: PreProcessorTest.java View source code
@Test
public void test() {
    GsonFireBuilder builder = new GsonFireBuilder().registerPreProcessor(A.class, new PreProcessor<A>() {

        @Override
        public void preDeserialize(Class<? extends A> clazz, JsonElement src, Gson gson) {
            src.getAsJsonObject().addProperty("a", "changed");
        }
    });
    Gson gson = builder.createGson();
    A a = new A();
    a.a = "a";
    a.b = "b";
    JsonObject json = gson.toJsonTree(a).getAsJsonObject();
    Assert.assertEquals(json.get("a").getAsString(), a.a);
    Assert.assertEquals(json.get("b").getAsString(), a.b);
    A a2 = gson.fromJson(json, A.class);
    Assert.assertEquals("changed", a2.a);
    Assert.assertEquals(a.b, a2.b);
}
Example 66
Project: hibernate-search-master  File: AnalysisJsonElementUnorderedArrayEquivalence.java View source code
private boolean containsAll(JsonArray containerToTest, JsonArray elementsToFind) {
    for (JsonElement elementToFind : elementsToFind) {
        boolean found = false;
        for (JsonElement candidate : containerToTest) {
            if (isNestedEquivalent(elementToFind, candidate)) {
                found = true;
                break;
            }
        }
        if (!found) {
            return false;
        }
    }
    return true;
}
Example 67
Project: intellij-plugins-master  File: KarmaWatcher.java View source code
@Override
public void handle(@NotNull JsonElement eventBody) {
    JsonArray patterns = eventBody.getAsJsonArray();
    final List<String> paths = ContainerUtil.newArrayListWithCapacity(patterns.size());
    for (JsonElement pattern : patterns) {
        JsonPrimitive p = pattern.getAsJsonPrimitive();
        paths.add(p.getAsString());
    }
    ApplicationManager.getApplication().executeOnPooledThread((Runnable) () -> mySession = new KarmaWatchSession(myServer, paths));
}
Example 68
Project: irma_android_cardproxy-master  File: ReaderMessageDeserializer.java View source code
@Override
public ReaderMessage deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    // TODO Auto-generated method stub
    ReaderMessage rm = new ReaderMessage(json.getAsJsonObject().get("type").getAsString(), json.getAsJsonObject().get("name").getAsString(), json.getAsJsonObject().get("id").getAsString());
    if (rm.type.equals("event")) {
        rm.arguments = context.deserialize(json.getAsJsonObject().get("arguments"), EventArguments.class);
    } else if (rm.type.equals("command")) {
        if (rm.name.equals("transmitCommandSet")) {
            rm.arguments = context.deserialize(json.getAsJsonObject().get("arguments"), TransmitCommandSetArguments.class);
        } else if (rm.name.equals("selectApplet")) {
            rm.arguments = context.deserialize(json.getAsJsonObject().get("arguments"), SelectAppletArguments.class);
        }
    }
    return rm;
}
Example 69
Project: ja-micro-master  File: EventUtils.java View source code
public static String getEventName(JsonObject event) {
    String eventName = null;
    if (event.has(META)) {
        eventName = event.getAsJsonObject(META).get(NAME).getAsString();
    } else {
        JsonElement eventType = event.get(EVENT_TYPE);
        if (eventType != null) {
            eventName = eventType.getAsString();
        }
    }
    return eventName;
}
Example 70
Project: java-apikit-master  File: TestData.java View source code
@Override
public TestData deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException {
    String roses = je.getAsJsonObject().get("roses").getAsString();
    String fish = je.getAsJsonObject().get("fish").getAsString();
    String sugar = je.getAsJsonObject().get("sugar").getAsString();
    Integer number = je.getAsJsonObject().get("number").getAsInt();
    TestData td = new TestData(roses, fish, sugar, number);
    return td;
}
Example 71
Project: javers-master  File: CommitPropertiesConverter.java View source code
static Map<String, String> fromJson(JsonElement json) {
    Map<String, String> properties = new HashMap<>();
    if (json != null) {
        for (JsonElement jsonElement : json.getAsJsonArray()) {
            JsonObject propertyObject = jsonElement.getAsJsonObject();
            String key = propertyObject.get(PROPERTY_KEY_FIELD).getAsString();
            String value = propertyObject.get(PROPERTY_VALUE_FIELD).getAsString();
            properties.put(key, value);
        }
    }
    return properties;
}
Example 72
Project: jconfig-master  File: BasicExtractor.java View source code
/*
     * (non-Javadoc)
     * 
     * @see
     * common.config.serializers.Extractor#extractObject(com.yahoo
     * .common.config.serializers.ObjectToJsonConverter, java.lang.Object)
     */
@Override
public JsonElement extractObject(ObjectToJsonConverter converter, Object value) throws AttributeNotFoundException {
    if (value.getClass().isAssignableFrom(String.class)) {
        return new JsonPrimitive((String) value);
    } else if (value.getClass().isAssignableFrom(Boolean.class)) {
        return new JsonPrimitive((Boolean) value);
    } else if (value.getClass().isAssignableFrom(Long.class)) {
        return new JsonPrimitive((Long) value);
    } else if (value.getClass().isAssignableFrom(Short.class)) {
        return new JsonPrimitive((Short) value);
    } else if (value.getClass().isAssignableFrom(Integer.class)) {
        return new JsonPrimitive((Integer) value);
    } else if (value.getClass().isAssignableFrom(Float.class)) {
        return new JsonPrimitive((Float) value);
    } else if (value.getClass().isAssignableFrom(Byte.class)) {
        return new JsonPrimitive((Byte) value);
    }
    throw new RuntimeException("Type " + value.getClass().getName() + "is not basic type");
}
Example 73
Project: jshoper3x-master  File: TimestampTypeAdapter.java View source code
@Override
public Timestamp deserialize(JsonElement json, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
    if (!(json instanceof JsonPrimitive)) {
        throw new JsonParseException("The date should be a string value");
    }
    try {
        Date date = format.parse(json.getAsString());
        return new Timestamp(date.getTime());
    } catch (ParseException e) {
        throw new JsonParseException(e);
    }
}
Example 74
Project: kairosdb-master  File: ComplexDataPointFactory.java View source code
@Override
public DataPoint getDataPoint(long timestamp, JsonElement json) throws IOException {
    if (json.isJsonObject()) {
        JsonObject object = json.getAsJsonObject();
        double real = object.get("real").getAsDouble();
        double imaginary = object.get("imaginary").getAsDouble();
        return new ComplexDataPoint(timestamp, real, imaginary);
    } else
        throw new IOException("JSON object is not a valid complex data point");
}
Example 75
Project: karamel-master  File: MachineEntitySerializer.java View source code
@Override
public JsonElement serialize(MachineRuntime machineEntity, Type type, JsonSerializationContext context) {
    final JsonObject jsonObj = new JsonObject();
    jsonObj.add("machine", context.serialize(machineEntity.getPublicIp()));
    jsonObj.add("life", context.serialize(machineEntity.getLifeStatus().toString()));
    jsonObj.add("tasksStatus", context.serialize(machineEntity.getTasksStatus().toString()));
    jsonObj.add("privateIp", context.serialize(machineEntity.getPrivateIp()));
    jsonObj.add("user", context.serialize(machineEntity.getSshUser()));
    jsonObj.add("port", context.serialize(machineEntity.getSshPort()));
    jsonObj.add("tasks", context.serialize(machineEntity.getTasks()));
    return jsonObj;
}
Example 76
Project: LIMO-master  File: MultiModeLegSerializer.java View source code
@Override
public JsonElement serialize(MultiModeLeg src, Type typeOfSrc, JsonSerializationContext context) {
    Gson g = GsonHelper.getInstance();
    Leg hLeg = new Leg(src);
    hLeg.setNext(src.getNext());
    JsonObject ele1 = (JsonObject) g.toJsonTree(hLeg);
    JsonArray array = new JsonArray();
    Map<Leg, Double> mapToSeri = src.getLegs();
    mapToSeri.entrySet().stream().map(( entrySet) -> {
        Leg key = entrySet.getKey();
        Double value = entrySet.getValue();
        JsonObject ele2 = new JsonObject();
        ele2.add("Leg", g.toJsonTree(key));
        ele2.addProperty("Value", value);
        return ele2;
    }).forEach(( ele2) -> {
        array.add(ele2);
    });
    ele1.add("Legs", array);
    return ele1;
}
Example 77
Project: metadata-mapper-master  File: XMPRootCollection.java View source code
public static void registerGsonHelper(final GsonBuilder gsonBuilder) {
    gsonBuilder.registerTypeAdapter(XMPRootCollection.class, new JsonSerializer<XMPRootCollection>() {

        @Override
        public JsonElement serialize(final XMPRootCollection xmpRootMetadataCollection, final Type type, final JsonSerializationContext jsonSerializationContext) {
            return jsonSerializationContext.serialize(xmpRootMetadataCollection.metadataItems);
        }
    });
}
Example 78
Project: metastone-master  File: SpellDescSerializer.java View source code
@Override
public JsonElement serialize(SpellDesc spell, Type type, JsonSerializationContext context) {
    JsonObject result = new JsonObject();
    result.add("class", new JsonPrimitive(spell.getSpellClass().getSimpleName()));
    for (SpellArg spellArg : SpellArg.values()) {
        if (spellArg == SpellArg.CLASS) {
            continue;
        }
        if (!spell.contains(spellArg)) {
            continue;
        }
        String argName = ParseUtils.toCamelCase(spellArg.toString());
        result.add(argName, new JsonPrimitive(spell.get(spellArg).toString()));
    }
    return result;
}
Example 79
Project: MHFC-master  File: DirectorUploadQuests.java View source code
public static String construct(QuestDescriptionRegistry data) throws IOException {
    StringWriter output = new StringWriter();
    JsonWriter jsonWrite = new JsonWriter(output);
    jsonWrite.setIndent("");
    JsonObject holderObject = new JsonObject();
    BuilderJsonToQuests builder = new BuilderJsonToQuests(data);
    JsonElement goalDescriptions = builder.retrieveGoalsAsJson();
    JsonElement questDescriptions = builder.retrieveQuestsAsJson();
    JsonElement groups = builder.retrieveGroupsAsJson();
    holderObject.add(MHFCQuestBuildRegistry.KEY_GOAL_DESCRIPTION, goalDescriptions);
    holderObject.add(MHFCQuestBuildRegistry.KEY_QUEST_DESCRIPTION, questDescriptions);
    holderObject.add(MHFCQuestBuildRegistry.KEY_GROUPS, groups);
    BuilderJsonToQuests.gsonInstance.toJson(holderObject, jsonWrite);
    jsonWrite.flush();
    return output.toString();
}
Example 80
Project: MineBans-master  File: OpenAppealsData.java View source code
public static OpenAppealsData fromString(String response) {
    OpenAppealsData appealsData = new OpenAppealsData();
    JsonObject object = parser.parse(response).getAsJsonObject();
    for (Entry<String, JsonElement> entry : object.get("disputes").getAsJsonObject().entrySet()) {
        AppealData data = gson.fromJson(entry.getValue(), AppealData.class);
        data.ban_reason = BanReason.getFromID(data.ban_reason_id);
        appealsData.appeals.add(data);
    }
    return appealsData;
}
Example 81
Project: MoeQuest-master  File: HuaBanMeizi.java View source code
/**
   * 解�json返回的数� 拼接为集�
   */
public static HuaBanMeizi createFromJson(String json) {
    HuaBanMeizi result = new Gson().fromJson(json, HuaBanMeizi.class);
    Iterator<Map.Entry<String, JsonElement>> iterator = result.list.entrySet().iterator();
    if (result.infos == null) {
        result.infos = new ArrayList<>();
    }
    while (iterator.hasNext()) {
        Map.Entry<String, JsonElement> element = iterator.next();
        try {
            result.infos.add(new Gson().fromJson(element.getValue(), HuaBanMeiziInfo.class));
        } catch (Exception e) {
        }
    }
    result.list = null;
    return result;
}
Example 82
Project: olca-app-master  File: ModelNodeBuilder.java View source code
private int getOrdinal(JsonNode node) {
    if (node.parent == null)
        return 0;
    JsonElement parent = node.parent.getElement();
    String type = ModelUtil.getType(parent);
    if (node.parent.getElement().isJsonArray()) {
        JsonObject obj = node.getElement().getAsJsonObject();
        if (obj.has("position")) {
            return obj.get("position").getAsInt();
        }
    }
    return PropertyLabels.getOrdinal(type, node.property);
}
Example 83
Project: opentele-client-android-master  File: DateSerializerTest.java View source code
@Test
public void deserializesDates() throws ParseException {
    JsonElement elementToDeserialize = new JsonPrimitive("2012-01-15T17:04:00.000+01:00");
    Date deserialized = serializer.deserialize(elementToDeserialize, Date.class, null);
    Date expectedDate = new SimpleDateFormat("yyyy-MM-dd hh:mm").parse("2012-01-15 17:04");
    assertEquals(expectedDate, deserialized);
}
Example 84
Project: Pearcel-Mod-master  File: VersionChecker.java View source code
@Override
public void run() {
    try {
        URL url = new URL("https://raw.githubusercontent.com/MiningMark48/Pearcel-Mod/master/src/main/resources/versioninfo.json");
        HttpURLConnection request = (HttpURLConnection) url.openConnection();
        request.connect();
        JsonParser jp = new JsonParser();
        JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
        JsonObject rootObj = root.getAsJsonObject();
        latestVersion = rootObj.get("version").getAsString();
        isLatestVersion = Reference.MOD_VERSION.equals(latestVersion);
    } catch (MalformedURLException e) {
        LogHelper.error("Malformed URL Exception! Report to mod author.");
    } catch (IOException e) {
        LogHelper.error("IO Exception! Report to mod author.");
    }
}
Example 85
Project: PneumaticCraft-master  File: AmadronOfferConfig.java View source code
@Override
protected final void readFromJson(JsonObject json) {
    readFromJsonCustom(json);
    JsonArray array = (JsonArray) json.get("offers");
    Collection<AmadronOffer> offers = getOffers();
    offers.clear();
    for (JsonElement element : array) {
        AmadronOffer offer = ((JsonObject) element).has("inStock") ? AmadronOfferCustom.fromJson((JsonObject) element) : AmadronOffer.fromJson((JsonObject) element);
        if (offer != null) {
            offers.add(offer);
        }
    }
}
Example 86
Project: RetrofitExample-master  File: ItemTypeAdapterFactory.java View source code
public T read(JsonReader in) throws IOException {
    JsonElement jsonElement = elementAdapter.read(in);
    if (jsonElement.isJsonObject()) {
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        if (jsonObject.has("cod") && jsonObject.get("cod").getAsInt() == 404) {
            throw new IllegalArgumentException(jsonObject.get("message").getAsString());
        }
    }
    return delegate.fromJsonTree(jsonElement);
}
Example 87
Project: Robin-Client-master  File: FileAnnotation.java View source code
@Override
public JsonElement toAnnotation() {
    JsonObject object = new JsonObject();
    JsonObject file = new JsonObject();
    JsonObject value = new JsonObject();
    file.addProperty("file_id", getFileId());
    file.addProperty("file_token", getFileToken());
    file.addProperty("format", "oembed");
    object.addProperty("type", "net.app.core.oembed");
    value.add("+net.app.core.file", file);
    object.add("value", value);
    return object;
}
Example 88
Project: robin-java-sdk-master  File: UrnAdapter.java View source code
@Override
public Urn deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    if (json.isJsonPrimitive()) {
        String urnString = json.getAsString();
        if (null != urnString && !"".equals(urnString)) {
            if (typeOfT == Urn.class) {
                try {
                    return Urn.create(urnString);
                } catch (URISyntaxException e) {
                    throw new JsonParseException(e);
                }
            }
        }
    }
    return null;
}
Example 89
Project: round-java-master  File: RequestSpec.java View source code
public static RequestSpec parse(JsonObject requestJson) {
    String type = null;
    if (requestJson.has(TYPE))
        type = requestJson.get(TYPE).getAsString();
    JsonElement authorizationsElement = requestJson.get(AUTHORIZATION);
    List<String> authorizations = new ArrayList<String>();
    if (authorizationsElement != null) {
        if (authorizationsElement.isJsonArray()) {
            JsonArray authorizationsJson = authorizationsElement.getAsJsonArray();
            for (JsonElement authorizationJson : authorizationsJson) {
                String authorization = authorizationJson.getAsString();
                authorizations.add(authorization);
            }
        } else {
            String authorization = authorizationsElement.getAsString();
            authorizations.add(authorization);
        }
    }
    return new RequestSpec(type, authorizations);
}
Example 90
Project: spacesimulator-master  File: KeplerianOrbitSerializer.java View source code
@Override
public void read(JsonObject object, KeplerianOrbit value, Gson gson) {
    JsonElement futureElement = object.get(FUTURE_MOVING_OBJECT);
    if (futureElement != null) {
        FutureMovingObject futureMovingObject = gson.fromJson(futureElement, FutureMovingObject.class);
        Assert.notNull(futureMovingObject);
        value.setReferenceFrame(futureMovingObject);
    } else {
        MovingObject mo = getNamedObject(object, CENTRAL_OBJECT);
        Assert.notNull(mo);
        value.setReferenceFrame(mo);
    }
}
Example 91
Project: stripe-java-master  File: FeeRefundCollectionDeserializer.java View source code
public FeeRefundCollection deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
    // API versions 2014-07-26 and earlier render application fee refunds as an array instead of an object
    if (json.isJsonArray()) {
        List<FeeRefund> refunds = gson.fromJson(json, REFUND_LIST_TYPE);
        FeeRefundCollection collection = new FeeRefundCollection();
        collection.setData(refunds);
        collection.setHasMore(false);
        collection.setTotalCount(refunds.size());
        return collection;
    } else {
        return gson.fromJson(json, typeOfT);
    }
}
Example 92
Project: Team11Prototype-master  File: BitMapTest.java View source code
/**
	* This is a test for BitmapConverter.
	* From the test below we can see that
	* BitmapConverter can both serizlize and deserizlize
	*
	*/
public void testLBitmapConverter() throws Exception {
    JsonElement jsonElement = bitmapConverter.serialize(bitmap, null, null);
    Bitmap newBitmap = bitmapConverter.deserialize(jsonElement, null, null);
    assertEquals(bitmap.getByteCount(), newBitmap.getByteCount());
    assertEquals(bitmap.getHeight(), newBitmap.getHeight());
    assertEquals(bitmap.getDensity(), newBitmap.getDensity());
    assertEquals(bitmap.getRowBytes(), newBitmap.getRowBytes());
    tearDown();
}
Example 93
Project: teamcity-plugins-master  File: GsonDateTypeAdapterTest.java View source code
@Test
public void deserialize() throws Exception {
    JsonElement jsonElement = mock(JsonElement.class);
    given(jsonElement.getAsJsonPrimitive()).willReturn(new JsonPrimitive("2015-07-29T17:31:29.962962+00:00"));
    GsonDateTypeAdapter typeAdapter = new GsonDateTypeAdapter();
    typeAdapter.deserialize(jsonElement, mock(Type.class), mock(JsonDeserializationContext.class));
}
Example 94
Project: threatconnect-java-master  File: EnumListJsonSerializer.java View source code
@Override
public List<T> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) {
    //holds the list of runlevel values to return
    List<T> values = new ArrayList<T>();
    //check to see if this element is an array
    if (json.isJsonArray()) {
        //for each of the elements in the json array
        for (JsonElement element : json.getAsJsonArray()) {
            values.add(EnumJsonSerializer.toEnum(element.getAsString(), enumClass));
        }
    } else //check to see if this object is a primitive
    if (json.isJsonPrimitive()) {
        values.add(EnumJsonSerializer.toEnum(json.getAsString(), enumClass));
    } else {
        throw new RuntimeException("Unexpected JSON type: " + json.getClass());
    }
    return values;
}
Example 95
Project: TinkersConstruct-master  File: TransformDeserializer.java View source code
@Override
public ImmutableMap<ItemCameraTransforms.TransformType, TRSRTransformation> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    JsonObject obj = json.getAsJsonObject();
    JsonElement texElem = obj.get(tag);
    if (texElem != null && texElem.isJsonObject()) {
        ItemCameraTransforms itemCameraTransforms = context.deserialize(texElem.getAsJsonObject(), ItemCameraTransforms.class);
        return IPerspectiveAwareModel.MapWrapper.getTransforms(itemCameraTransforms);
    }
    return ImmutableMap.of();
}
Example 96
Project: TwAndroid-master  File: DeserializeWorkoutHolder.java View source code
@Override
public List<WorkoutHolderModel> deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException {
    JsonElement workoutHolder = je.getAsJsonObject().get("data");
    Type listType = new TypeToken<List<WorkoutHolderModel>>() {
    }.getType();
    List<WorkoutHolderModel> workoutHolders = new Gson().fromJson(workoutHolder, listType);
    JsonArray workouts = workoutHolder.getAsJsonArray();
    int index = 0;
    for (JsonElement workout : workouts) {
        List<WorkoutsExercisesModel> workoutExercises = new ArrayList<WorkoutsExercisesModel>();
        JsonElement exercises = workout.getAsJsonObject().get("exercises");
        for (JsonElement exercise : exercises.getAsJsonArray()) {
            WorkoutsExercisesModel exe = new Gson().fromJson(exercise.getAsJsonObject().get("exercise"), WorkoutsExercisesModel.class);
            workoutExercises.add(exe);
        }
        workoutHolders.get(index).setExercises(workoutExercises);
        index++;
    }
    return workoutHolders;
}
Example 97
Project: tzatziki-master  File: StepContainerDeserializer.java View source code
@Override
public StepContainer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    JsonPrimitive typeAsJson = json.getAsJsonObject().getAsJsonPrimitive(TYPE);
    if (typeAsJson != null) {
        String type = typeAsJson.getAsString();
        if (type.equals(SCENARIO))
            return delegate.fromJson(json, ScenarioExec.class);
        else if (type.equals(SCENARIO_OUTLINE))
            return delegate.fromJson(json, ScenarioOutlineExec.class);
    }
    // fallback?
    return delegate.fromJson(json, ScenarioExec.class);
}
Example 98
Project: weixin-java-tools-master  File: WxMpMaterialArticleUpdateGsonAdapter.java View source code
public JsonElement serialize(WxMpMaterialArticleUpdate wxMpMaterialArticleUpdate, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject articleUpdateJson = new JsonObject();
    articleUpdateJson.addProperty("media_id", wxMpMaterialArticleUpdate.getMediaId());
    articleUpdateJson.addProperty("index", wxMpMaterialArticleUpdate.getIndex());
    articleUpdateJson.add("articles", WxMpGsonBuilder.create().toJsonTree(wxMpMaterialArticleUpdate.getArticles(), WxMpMaterialNews.WxMpMaterialNewsArticle.class));
    return articleUpdateJson;
}
Example 99
Project: writelatex-git-bridge-master  File: PushResult.java View source code
@Override
public void fromJSON(JsonElement json) {
    JsonObject responseObject = json.getAsJsonObject();
    String code = Util.getCodeFromResponse(responseObject);
    if (code.equals("accepted")) {
        success = true;
    } else if (code.equals("outOfDate")) {
        success = false;
    } else {
        throw new RuntimeException();
    }
}
Example 100
Project: xdi2-master  File: JSONLiteralNode.java View source code
@Override
public Object getLiteralData() {
    JSONContextNode jsonContextNode = (JSONContextNode) this.getContextNode();
    JsonObject jsonObject = ((JSONGraph) this.getGraph()).jsonLoad(jsonContextNode.getXDIAddress().toString());
    JsonElement jsonElement = jsonObject.get(XDIConstants.XDI_ARC_LITERAL.toString());
    if (jsonElement == null) {
        log.warn("In literal node " + this.getContextNode() + " found non-existent value.");
        return null;
    }
    return AbstractLiteralNode.jsonElementToLiteralData(jsonElement);
}
Example 101
Project: XenMaster-master  File: HookTest.java View source code
/**
     * Test of execute method, of class Hook.
     */
@Test
public void testExecute() {
    Hook.APICall apic = new Hook.APICall();
    apic.args = new Object[0];
    apic.ref = "";
    Gson gson = new Gson();
    JsonElement json = gson.toJsonTree(apic);
    Command cmd = new Command("xen", "Session[].getThisHost", apic);
    Object o = hook.execute(cmd);
    assertNotNull(o);
    Host s = (Host) o;
    System.out.println("Your current host id: " + s.getUUID().toString());
}