Java Code Examples for com.google.gson.Gson#toJsonTree()

The following examples show how to use com.google.gson.Gson#toJsonTree() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LogAnalyzerUtil.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
/***
 * This method process debug report and make it in form of json string so that it can be views on UI.
 * @param debugAnalysisMap
 * @param debugAnalysisBean
 * @return 
 */
private String getJsonFromDebugReport(Map<String, DebugAnalysisBean> debugAnalysisMap,DebugAnalysisBean debugAnalysisBean) {
	final Gson gson = new Gson();
	String jsonFromReport=null;
	try {
		JsonObject jsonObject = gson.toJsonTree(debugAnalysisMap)
				.getAsJsonObject();
		DebugReport debugReport = new DebugReportGenerator()
				.generateReportFromDebugAnalysisBean(debugAnalysisBean);
		JsonElement jsonElement = gson.toJsonTree(debugReport,
				DebugReport.class);
		jsonObject.add(LPConstants.DEBUGGER_SUMMARY, jsonElement);
		jsonFromReport = jsonObject.toString();
	} catch (Exception e) {
		LOGGER.error("Exception while creating the Json object with appended Debugger Summary",e);
		jsonFromReport = gson.toJson(debugAnalysisMap);
	}
	LOGGER.debug("Completed debugger log processing");
	return jsonFromReport;
}
 
Example 2
Source File: Pricing.java    From amadeus-java with MIT License 5 votes vote down vote up
/**
 * Build the FlightOffers JSON.
 * @param flightOffersSearches list of FlightOfferSearch to price
 * @return a JsonArray representation of the object FlightOffersSearch
 */
private JsonArray buildFlightOffersJSON(FlightOfferSearch[] flightOffersSearches) {
  Gson gson = new GsonBuilder().create();
  JsonArray flightOffersArray = new JsonArray();
  // Add each flightOffersSearch to the array
  for (int i = 0; i < flightOffersSearches.length; i++) {
    JsonElement flightOffer = gson.toJsonTree(flightOffersSearches[i], FlightOfferSearch.class);
    flightOffersArray.add(flightOffer);
  }
  return flightOffersArray;
}
 
Example 3
Source File: NotificationGroupsList.java    From StatsAgg with Apache License 2.0 5 votes vote down vote up
/**
 * Returns json containing a list of notification groups.
 * 
 * @param request servlet request
 * @return list of notification groups
 */ 
protected String getNotificationGroupsList(HttpServletRequest request) {
    
    if (request == null) {
        return Helper.ERROR_UNKNOWN_JSON;
    }
    
    try {
        NotificationGroupsDao notificationGroupsDao = new NotificationGroupsDao();
        List<NotificationGroup> notificationGroups = notificationGroupsDao.getAllDatabaseObjectsInTable();
        if (notificationGroups == null) notificationGroups = new ArrayList<>();
        
        List<JsonObject> notificationGroupsJsonObjects = new ArrayList<>();
        for (NotificationGroup notificationGroup : notificationGroups) {
            JsonObject notificationGroupJsonObject = NotificationGroup.getJsonObject_ApiFriendly(notificationGroup);
            if (notificationGroupJsonObject != null) notificationGroupsJsonObjects.add(notificationGroupJsonObject);
        }
        
        Gson notificationGroupsGson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
        JsonElement notificationGroups_JsonElement = notificationGroupsGson.toJsonTree(notificationGroupsJsonObjects);
        JsonArray jsonArray = new Gson().toJsonTree(notificationGroups_JsonElement).getAsJsonArray();
        String notificationGroupsJson = notificationGroupsGson.toJson(jsonArray);
        
        return notificationGroupsJson;
    }
    catch (Exception e) {
        logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
        return Helper.ERROR_UNKNOWN_JSON;
    }
    
}
 
Example 4
Source File: NavigationTest.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void toJSON() throws Exception {
    Gson gson = new Gson();
    JsonElement jsonElement = gson.toJsonTree(this.navigation);
    JsonObject navigationObject = jsonElement.getAsJsonObject();

    assertEquals("template_mysample", navigationObject.get("template").getAsString());
    assertEquals("/content", navigationObject.get("dir").getAsString());
    assertEquals("History Title", navigationObject.get("historyTitle").getAsString());
    assertEquals("/content/below/index.xml", navigationObject.get("hrefStartingPage").getAsString());
    assertEquals("Main Title", navigationObject.get("mainTitle").getAsString());
}
 
Example 5
Source File: NotificationGroup.java    From StatsAgg with Apache License 2.0 5 votes vote down vote up
public static JsonObject getJsonObject_ApiFriendly(NotificationGroup notificationGroup) {
    
    if (notificationGroup == null) {
        return null;
    }
    
    try {
        Gson notificationGroup_Gson = new GsonBuilder().setFieldNamingStrategy(new JsonOutputFieldNamingStrategy()).setPrettyPrinting().create();   
        JsonElement notificationGroup_JsonElement = notificationGroup_Gson.toJsonTree(notificationGroup);
        JsonObject jsonObject = new Gson().toJsonTree(notificationGroup_JsonElement).getAsJsonObject();
        
        JsonArray emailAddresses_JsonArray = new JsonArray();
        List<String> emailAddresses_List = notificationGroup.getEmailAddressesList();
        
        if (emailAddresses_List != null) {
            for (String emailAddress : emailAddresses_List) {
                if (emailAddress == null) continue;
                emailAddresses_JsonArray.add(emailAddress.trim());
            }
        }
                
        jsonObject.remove("email_addresses");
        jsonObject.add("email_addresses", emailAddresses_JsonArray);
        
        return jsonObject;
    }
    catch (Exception e) {
        logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
        return null;
    }
    
}
 
Example 6
Source File: CustomSerializerTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testSubClassSerializerInvokedForBaseClassFieldsHoldingSubClassInstances() {
  Gson gson = new GsonBuilder()
      .registerTypeAdapter(Base.class, new BaseSerializer())
      .registerTypeAdapter(Sub.class, new SubSerializer())
      .create();
  ClassWithBaseField target = new ClassWithBaseField(new Sub());
  JsonObject json = (JsonObject) gson.toJsonTree(target);
  JsonObject base = json.get("base").getAsJsonObject();
  assertEquals(SubSerializer.NAME, base.get(Base.SERIALIZER_KEY).getAsString());
}
 
Example 7
Source File: ApiSteps.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * В json строке, сохраннённой в переменной, происходит поиск значений по jsonpath из первого столбца таблицы.
 * Полученные значения сравниваются с ожидаемым значением во втором столбце таблицы.
 * Шаг работает со всеми типами json элементов: объекты, массивы, строки, числа, литералы true, false и null.
 */
@Тогда("^в json (?:строке|файле) \"([^\"]*)\" значения, найденные по jsonpath, равны значениям из таблицы$")
@Then("^values from json (?:string|file) named \"([^\"]*)\" found via jsonpath are equal to the values from the table$")
public void checkValuesInJsonAsString(String jsonVar, DataTable dataTable) {
    String strJson = loadValueFromFileOrPropertyOrVariableOrDefault(jsonVar);
    Gson gsonObject = new Gson();
    JsonParser parser = new JsonParser();
    ReadContext ctx = JsonPath.parse(strJson, createJsonPathConfiguration());
    boolean error = false;
    for (List<String> row : dataTable.raw()) {
        String jsonPath = row.get(0);
        JsonElement actualJsonElement;
        try {
            actualJsonElement = gsonObject.toJsonTree(ctx.read(jsonPath));
        } catch (PathNotFoundException e) {
            error = true;
            continue;
        }
        JsonElement expectedJsonElement = parser.parse(row.get(1));
        if (!actualJsonElement.equals(expectedJsonElement)) {
            error = true;
        }
        akitaScenario.write("JsonPath: " + jsonPath + ", ожидаемое значение: " + expectedJsonElement + ", фактическое значение: " + actualJsonElement);
    }
    if (error)
        throw new RuntimeException("Ожидаемые и фактические значения в json не совпадают");
}
 
Example 8
Source File: CustomSerializerTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testBaseClassSerializerInvokedForBaseClassFields() {
  Gson gson = new GsonBuilder()
      .registerTypeAdapter(Base.class, new BaseSerializer())
      .registerTypeAdapter(Sub.class, new SubSerializer())
      .create();
  ClassWithBaseField target = new ClassWithBaseField(new Base());
  JsonObject json = (JsonObject) gson.toJsonTree(target);
  JsonObject base = json.get("base").getAsJsonObject();
  assertEquals(BaseSerializer.NAME, base.get(Base.SERIALIZER_KEY).getAsString());
}
 
Example 9
Source File: CustomSerializerTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testSerializerReturnsNull() {
  Gson gson = new GsonBuilder()
    .registerTypeAdapter(Base.class, new JsonSerializer<Base>() {
      public JsonElement serialize(Base src, Type typeOfSrc, JsonSerializationContext context) {
        return null;
      }
    })
    .create();
    JsonElement json = gson.toJsonTree(new Base());
    assertTrue(json.isJsonNull());
}
 
Example 10
Source File: ServerResponsesFactory.java    From devicehive-java-server with Apache License 2.0 5 votes vote down vote up
public static DeviceNotification createNotificationForDevice(DeviceVO device, String notificationName) {
    DeviceNotification notification = new DeviceNotification();
    notification.setId(Math.abs(new Random().nextInt())); // TODO: remove this when id generation will be moved to backend
    notification.setNotification(notificationName);
    notification.setDeviceId(device.getDeviceId());
    Gson gson = GsonFactory.createGson(DEVICE_PUBLISHED);
    JsonElement deviceAsJson = gson.toJsonTree(device);
    JsonStringWrapper wrapperOverDevice = new JsonStringWrapper(deviceAsJson.toString());
    notification.setParameters(wrapperOverDevice);
    return notification;
}
 
Example 11
Source File: StreamData.java    From MultiChainJavaAPI with GNU General Public License v3.0 5 votes vote down vote up
protected JsonObject getJsonValue(Object object) {
  final GsonBuilder builder = new GsonBuilder();
  final Gson gson = builder.create();

  JsonElement jsonElement = gson.toJsonTree(object);
  JsonObject jsonObject = (JsonObject) jsonElement;
  // property removal
  jsonObject.remove("property");

  return jsonObject;
}
 
Example 12
Source File: CustomSerializerTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testSubClassSerializerInvokedForBaseClassFieldsHoldingArrayOfSubClassInstances() {
  Gson gson = new GsonBuilder()
      .registerTypeAdapter(Base.class, new BaseSerializer())
      .registerTypeAdapter(Sub.class, new SubSerializer())
      .create();
  ClassWithBaseArrayField target = new ClassWithBaseArrayField(new Base[] {new Sub(), new Sub()});
  JsonObject json = (JsonObject) gson.toJsonTree(target);
  JsonArray array = json.get("base").getAsJsonArray();
  for (JsonElement element : array) {
    JsonElement serializerKey = element.getAsJsonObject().get(Base.SERIALIZER_KEY);
   assertEquals(SubSerializer.NAME, serializerKey.getAsString());
  }
}
 
Example 13
Source File: FlightOrders.java    From amadeus-java with MIT License 5 votes vote down vote up
/**
 * Build the JSON from the Travelers array.
 *
 * @param travelers array of Traveler
 * @return
 */
private JsonArray buildTravelersJSON(Traveler[] travelers) {
  Gson gson = new GsonBuilder().create();
  JsonArray travelerArray = new JsonArray();

  for (int i = 0; i < travelers.length; i++) {
    JsonElement traveler = gson.toJsonTree(travelers[i], Traveler.class);
    travelerArray.add(traveler);
  }
  return travelerArray;
}
 
Example 14
Source File: JsonUtils.java    From mogu_blog_v2 with Apache License 2.0 5 votes vote down vote up
/**
 * 将map转换成pojo
 *
 * @param map
 * @param beanType
 * @param <T>
 * @return
 * @date 2020年1月16日11:05:51
 */
public static <T> T mapToPojo(Map<String, Object> map, Class<T> beanType) {

    Gson gson = new GsonBuilder()
            .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
            .setDateFormat("yyyy-MM-dd HH:mm:ss")
            .serializeNulls()
            .create();

    JsonElement jsonElement = gson.toJsonTree(map);
    T pojo = gson.fromJson(jsonElement, beanType);

    return pojo;
}
 
Example 15
Source File: PublicKeyCredentialRpEntity.java    From webauthndemo with Apache License 2.0 4 votes vote down vote up
@Override
public JsonObject getJsonObject() {
  Gson gson = new Gson();
  return (JsonObject) gson.toJsonTree(this);
}
 
Example 16
Source File: LettuceJsonDumper.java    From sherlock with GNU General Public License v3.0 4 votes vote down vote up
@Override
public List<ImmutablePair<String, String>> getQueuedJobs() throws IOException {
    try (
        RedisConnection<String> conn = connect();
        RedisConnection<byte[]> binary = binary()
    ) {
        List<RedisFuture> futures = new LinkedList<>();
        AsyncCommands<String> cmd = conn.async();
        AsyncCommands<byte[]> bin = binary.async();
        cmd.setAutoFlushCommands(false);
        bin.setAutoFlushCommands(false);
        StoreParams params = Store.getParamsFor(Store.AccessorType.ANOMALY_REPORT);
        String queueName = DatabaseConstants.QUEUE_JOB_SCHEDULE;
        String pendingQueueName = queueName + "Pending";
        queueName = String.format("{queue}.%s", queueName);
        pendingQueueName = String.format("{queue}.%s", pendingQueueName);
        RedisFuture<List<ScoredValue<String>>> jobQueue = cmd.zrangeWithScores(
            queueName, 0, -1
        );
        RedisFuture<List<ScoredValue<String>>> pendingQueue = cmd.zrangeWithScores(
            pendingQueueName + "Pending", 0, -1
        );
        futures.add(jobQueue);
        futures.add(pendingQueue);
        cmd.flushCommands();
        awaitRaw(futures);
        futures.clear();
        Gson gson = new Gson();
        List<ImmutablePair<String, String>> result = new ArrayList<>();
        JsonElement queueEl = gson.toJsonTree(jobQueue.get(), new TypeToken<List<ScoredValue<String>>>() { }.getType());
        JsonElement pendingEl = gson.toJsonTree(pendingQueue.get(), new TypeToken<List<ScoredValue<String>>>() { }.getType());
        JsonArray queueArray = queueEl.getAsJsonArray();
        JsonArray pendingQueueArray = pendingEl.getAsJsonArray();
        for (int i = 0; i < queueArray.size(); i++) {
            result.add(extractJobDetails(queueArray.get(i)));
        }
        for (int i = 0; i < pendingQueueArray.size(); i++) {
            result.add(extractJobDetails(pendingQueueArray.get(i)));
        }
        return result;
    } catch (InterruptedException | ExecutionException e) {
        log.error("Error while retrieving Redis database!", e);
        throw new IOException(e.getMessage(), e);
    }
}
 
Example 17
Source File: SharedPreferencesUtil.java    From styT with Apache License 2.0 4 votes vote down vote up
/**
 * 用于保存集合
 *
 * @param key  key
 * @param list 集合数据
 * @return 保存结果
 */
public static <T> boolean putListData(String key, List<T> list) {
    boolean result;
    String type = list.get(0).getClass().getSimpleName();
    SharedPreferences.Editor editor = sp.edit();
    JsonArray array = new JsonArray();
    try {
        switch (type) {
            case "Boolean":
                for (int i = 0; i < list.size(); i++) {
                    array.add((Boolean) list.get(i));
                }
                break;
            case "Long":
                for (int i = 0; i < list.size(); i++) {
                    array.add((Long) list.get(i));
                }
                break;
            case "Float":
                for (int i = 0; i < list.size(); i++) {
                    array.add((Float) list.get(i));
                }
                break;
            case "String":
                for (int i = 0; i < list.size(); i++) {
                    array.add((String) list.get(i));
                }
                break;
            case "Integer":
                for (int i = 0; i < list.size(); i++) {
                    array.add((Integer) list.get(i));
                }
                break;
            default:
                Gson gson = new Gson();
                for (int i = 0; i < list.size(); i++) {
                    JsonElement obj = gson.toJsonTree(list.get(i));
                    array.add(obj);
                }
                break;
        }
        editor.putString(key, array.toString());
        result = true;
    } catch (Exception e) {
        result = false;
        e.printStackTrace();
    }
    editor.apply();
    return result;
}
 
Example 18
Source File: DexUtil.java    From Inspeckage with Apache License 2.0 4 votes vote down vote up
public static void saveClassesWithMethodsJson(XC_LoadPackage.LoadPackageParam loadPackageParam, SharedPreferences prefs) throws Throwable {

        String packageName = prefs.getString("package", "");
        Map<String, ArrayList<String>> classes = DexUtil.getClassesWithMethods(loadPackageParam, packageName);

        //RAIZ
        ClassMethod root = new ClassMethod();
        root.setID("p_" + packageName);
        root.setName(packageName);

        int c_id = 0;
        for (String classNameComplete : classes.keySet()) {

            if (classNameComplete.contains(packageName)) {
                c_id++;
                String pack_name = classNameComplete.substring(0, classNameComplete.lastIndexOf("."));
                String class_name = classNameComplete.substring(classNameComplete.lastIndexOf(".") + 1);

                //pacote
                ClassMethod package_class = new ClassMethod();
                package_class.setID(pack_name);
                package_class.setName(pack_name);

                if (!root.contains(package_class)) {
                    root.getClassMethods().add(package_class);
                }

                //classe
                ClassMethod class_leaf = new ClassMethod();
                class_leaf.setID(classNameComplete);
                class_leaf.setName(class_name);

                //adiciona metodos nas folhas(ultimas classes)
                ArrayList<String> methods = classes.get(classNameComplete);
                int m_id = 0;
                for (String method : methods) {
                    m_id++;
                    ClassMethod m = new ClassMethod();
                    m.setID("m_" + c_id+"_"+m_id);//
                    m.setName(method);
                    m.setIcon("jstree-file");
                    if (!class_leaf.contains(m)) {
                        class_leaf.getClassMethods().add(m);
                    }
                }

                package_class.getClassMethods().add(class_leaf);
                root.update(package_class);

            } else {

                /**String name = classNameComplete.substring(0,classNameComplete.lastIndexOf("."));

                 ClassMethod cx = new ClassMethod();
                 cx.setID(name);
                 cx.setName(name);

                 if(!array.contains(cx)){
                 //c.getClassMethods().add(cx);
                 }**/
            }
        }

        Gson gson = new GsonBuilder().create();
        JsonElement jsonElement = gson.toJsonTree(root);
        JsonObject jsonObject = jsonElement.getAsJsonObject();

        FileUtil.writeToFile(prefs, jsonObject.toString(), FileType.APP_STRUCT, "");
    }
 
Example 19
Source File: TestCmsApi.java    From fenixedu-cms with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected JsonElement removeNullKeys(JsonElement elem) {
    Gson builder = new GsonBuilder().create();
    return builder.toJsonTree(elem);
}
 
Example 20
Source File: GsonConfigParserTest.java    From java-sdk with Apache License 2.0 3 votes vote down vote up
@Test
public void parseAudienceCondition() throws Exception {
    JsonObject jsonObject = new JsonObject();

    Gson gson = new Gson();


    JsonElement leaf = gson.toJsonTree("1");

    jsonObject.add("audienceConditions", leaf);
    Condition condition = GsonHelpers.parseAudienceConditions(jsonObject);

    assertNotNull(condition);
}