List of usage examples for com.google.gson GsonBuilder setPrettyPrinting
public GsonBuilder setPrettyPrinting()
From source file:com.eclipsesource.connect.serialization.GsonFactory.java
License:Open Source License
public static Gson create(boolean prettyPrinting) { GsonBuilder builder = new GsonBuilder(); if (prettyPrinting) { builder.setPrettyPrinting(); }//from w ww. j a v a 2 s . com builder.registerTypeAdapter(Id.class, new IdTypeAdapter()); Converters.registerAll(builder); addFieldNamingStrategy(builder); return builder.create(); }
From source file:com.ethercis.ehr.knowledge.CacheKnowledgeService.java
License:Apache License
@QuerySetting(dialect = { @QuerySyntax(mode = I_ServiceRunMode.DialectSpace.STANDARD, httpMethod = "GET", method = "get", path = "vehr/template/example", responseType = ResponseType.Json), @QuerySyntax(mode = I_ServiceRunMode.DialectSpace.EHRSCAPE, httpMethod = "GET", method = "get", path = "rest/v1/template/example", responseType = ResponseType.Json) }) public Object example(I_SessionClientProperties props) throws ServiceManagerException { String templateId = props.getClientProperty(I_CacheKnowledgeService.TEMPLATE_ID, (String) null); String format = props.getClientProperty(I_CacheKnowledgeService.FORMAT, "XML"); if (templateId == null) throw new ServiceManagerException(global, SysErrorCode.INTERNAL_ILLEGALARGUMENT, ME, "No template Id give (templateId missing)"); Object retObj = null;//from w w w. ja v a2 s . c o m try { I_ContentBuilder contentBuilder = I_ContentBuilder.getInstance(null, I_ContentBuilder.OPT, this.getKnowledgeCache(), templateId); Object generated = contentBuilder.generate(); if (generated == null) throw new ServiceManagerException(global, SysErrorCode.INTERNAL_ILLEGALARGUMENT, ME, "Could not generate an example for template Id:" + templateId); if (generated instanceof Composition) { EventContext context = ContextHelper.createDummyContext(); PartyIdentified partyIdentified = CompositionAttributesHelper.createComposer("Composer", "ETHERCIS", "1234-5678"); ((Composition) generated).setContext(context); ((Composition) generated).setComposer(partyIdentified); ((Composition) generated) .setUid(new ObjectVersionID(UUID.randomUUID() + "::example.ethercis.com::1")); switch (format) { case "XML": global.getProperty().set(MethodName.RETURN_TYPE_PROPERTY, "" + MethodName.RETURN_XML); byte[] exportXml = contentBuilder.exportCanonicalXML((Composition) generated, true, true); if (exportXml == null) throw new ServiceManagerException(global, SysErrorCode.INTERNAL_ILLEGALARGUMENT, ME, "Could not export an example for template Id:" + templateId); retObj = new String(exportXml); break; case "ECISFLAT": global.getProperty().set(MethodName.RETURN_TYPE_PROPERTY, "" + MethodName.RETURN_STRING); Map<String, String> testRetMap = EcisFlattener.renderFlat((Composition) generated, true, CompositionSerializer.WalkerOutputMode.PATH); GsonBuilder builder = new GsonBuilder(); Gson gson = builder.setPrettyPrinting().disableHtmlEscaping().create(); String jsonString = gson.toJson(testRetMap); retObj = jsonString; break; case "FLAT": global.getProperty().set(MethodName.RETURN_TYPE_PROPERTY, "" + MethodName.RETURN_STRING); I_FlatJsonCompositionConverter flatJsonCompositionConverter = FlatJsonCompositionConverter .getInstance(cache); Map<String, Object> retMap = flatJsonCompositionConverter.fromComposition(templateId, (Composition) generated, true); jsonString = JsonUtil.toJsonString(retMap); retObj = jsonString; break; } } else if (generated instanceof Locatable) { switch (format) { case "XML": global.getProperty().set(MethodName.RETURN_TYPE_PROPERTY, "" + MethodName.RETURN_XML); byte[] exportXml = contentBuilder.exportCanonicalXML((Locatable) generated, true, true); if (exportXml == null) throw new ServiceManagerException(global, SysErrorCode.INTERNAL_ILLEGALARGUMENT, ME, "Could not export an example for template Id:" + templateId); retObj = new String(exportXml); break; case "ECISFLAT": global.getProperty().set(MethodName.RETURN_TYPE_PROPERTY, "" + MethodName.RETURN_JSON); Map<String, String> testRetMap = EcisFlattener.renderFlat((Locatable) generated, true, CompositionSerializer.WalkerOutputMode.PATH); GsonBuilder builder = new GsonBuilder(); Gson gson = builder.setPrettyPrinting().disableHtmlEscaping().create(); String jsonString = gson.toJson(testRetMap); retObj = jsonString; break; } } } catch (Exception e) { throw new ServiceManagerException(global, SysErrorCode.INTERNAL_ILLEGALARGUMENT, ME, "Could not generate templates list, reason:" + e); } return retObj; }
From source file:com.g3net.tool.ObjectUtils.java
License:Apache License
public static String toString(Object obj) { GsonBuilder builder = new GsonBuilder(); builder.serializeNulls();/* ww w . j ava 2 s . c o m*/ builder.disableHtmlEscaping(); builder.setPrettyPrinting(); Gson gson = builder.create(); return gson.toJson(obj); }
From source file:com.g3net.tool.ObjectUtils.java
License:Apache License
/** * //from w w w. j a v a 2 s . c o m * @param obj * @param type * Type typeOfT = new com.google.gson.reflect.TypeToken<Collection<Foo>>(){}.getType(); * @return */ public static String toString(Object obj, Type type) { GsonBuilder builder = new GsonBuilder(); builder.serializeNulls(); builder.disableHtmlEscaping(); builder.setPrettyPrinting(); Gson gson = builder.create(); return gson.toJson(obj, type); }
From source file:com.ghjansen.cas.ui.desktop.manager.EventManager.java
License:Open Source License
public EventManager(Main main) { this.main = main; this.skipRuleNumberEvent = false; this.invalidFieldColor = Color.red; this.validator = new GUIValidator(main, invalidFieldColor); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(UnidimensionalSimulationParameter.class, new SimulationParameterJsonAdapter<UnidimensionalSimulationParameter>()); gsonBuilder.setPrettyPrinting(); this.gson = gsonBuilder.create(); this.notification = new Notification(this); }
From source file:com.github.easyjsonapi.core.EasyJsonApi.java
License:Apache License
/** * Convert one {@link JsonApi} object into json api string with resource * objects inside the object// w w w. ja va 2s. com * * @param json * the json api object * @param classes * the classes utilized inside the object * @return the string with json api format * @throws EasyJsonApiException */ public String convertJsonApiToString(JsonApi json, Class<?>... classes) throws EasyJsonApiException { if (Assert.isNull(json)) { return null; } GsonBuilder builder = new GsonBuilder(); builder.setPrettyPrinting(); if (Assert.isNull(this.easyJsonApiConfig)) { setConfigDefault(); } this.serializerJsonApi.setConfig(this.easyJsonApiConfig); this.serializerJsonApi.setClassesUsed(classes); builder.registerTypeAdapter(JsonApi.class, this.serializerJsonApi); String jsonApi = null; try { jsonApi = builder.create().toJson(json); } catch (JsonSyntaxException ex) { throw new EasyJsonApiMalformedJsonException("Problem with json sended!", ex); } return jsonApi; }
From source file:com.github.easyjsonapi.core.EasyJsonApi.java
License:Apache License
/** * Convert one string into {@link JsonApi} object with classes resource * objects inside the object/*from www . j a v a 2 s . c o m*/ * * @param json * the json api string * @param classes * the classes utilized inside the object * @return the {@link JsonApi} object * @throws EasyJsonApiException */ public JsonApi convertStringToJsonApi(String json, Class<?>... classes) throws EasyJsonApiException { GsonBuilder builder = new GsonBuilder(); builder.setPrettyPrinting(); if (Assert.isNull(this.easyJsonApiConfig)) { setConfigDefault(); } this.deserializerJsonApi.setConfig(this.easyJsonApiConfig); this.deserializerJsonApi.setClassesUsed(classes); builder.registerTypeAdapter(JsonApi.class, this.deserializerJsonApi); JsonApi jsonApi = null; try { jsonApi = builder.create().fromJson(json, JsonApi.class); } catch (JsonSyntaxException ex) { throw new EasyJsonApiMalformedJsonException("Problem with json sended!", ex); } if (Assert.notNull(jsonApi)) { List<Data> cloneData = jsonApi.getData(); List<Error> cloneError = jsonApi.getErrors(); // Return null when doesn't exist errors and data if (cloneError.isEmpty() && cloneData.isEmpty()) { return null; } else if (!cloneData.isEmpty()) { // Get the first object inside the data and check if has any // attribute instanced Data firstData = cloneData.get(BigDecimal.ZERO.intValue()); // if (Assert.isNull(firstData.getId(), firstData.getType(), firstData.getAttr(), firstData.getRels(), firstData.getLinks())) { // return null; // } if (Assert.isNull(firstData.getId(), firstData.getType(), firstData.getAttr())) { return null; } } else if (!cloneError.isEmpty()) { // Get the first object inside the errors and check if has any // error instanced Error firstError = cloneError.get(BigDecimal.ZERO.intValue()); if (Assert.isNull(firstError.getId(), firstError.getTitle(), firstError.getDetail(), firstError.getCode(), firstError.getMeta(), firstError.getSource(), firstError.getStatus())) { return null; } } } return jsonApi; }
From source file:com.github.zhizheng.json.JsonSchemaGeneratorImpl.java
License:Apache License
/** * Json to Json Schema//w w w.ja v a 2 s . co m * * @param jsonElement * @return */ private String fromJsonElement(JsonElement jsonElement) { GsonBuilder gsonBuilder = new GsonBuilder(); if (jsonSchemaConfig.isPrettyPrint()) { gsonBuilder.setPrettyPrinting(); } gsonBuilder.disableHtmlEscaping(); Gson gson = gsonBuilder.create(); JsonObject jsonSchemaElement = makeSchemaElement(jsonElement, null, true, null); String jsonSchemaString = gson.toJson(jsonSchemaElement); return jsonSchemaString; }
From source file:com.github.zk1931.pulsefs.Utils.java
License:Apache License
public static String toJson(Object obj) { GsonBuilder builder = new GsonBuilder(); Gson gson = builder.setPrettyPrinting().create(); return gson.toJson(obj); }
From source file:com.google.api.ads.adwords.keywordoptimizer.api.JsonUtil.java
License:Open Source License
/** * Initializes Gson to convert objects to and from JSON. This method customizes a "plain" Gson by * adding appropriate exclusions strategies / adapters as needed in this project for a "pretty" * output. //from ww w .j a va2s . c o m */ private static Gson initGson(boolean prettyPrint) { GsonBuilder builder = new GsonBuilder(); // Exclude superclasses. ExclusionStrategy superclassExclusionStrategy = new SuperclassExclusionStrategy(); builder.addDeserializationExclusionStrategy(superclassExclusionStrategy); builder.addSerializationExclusionStrategy(superclassExclusionStrategy); // Exclude underscore fields in client lib objects. ExclusionStrategy underscoreExclusionStrategy = new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes field) { if (field.getName().startsWith("_")) { return true; } return false; } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }; builder.addDeserializationExclusionStrategy(underscoreExclusionStrategy); builder.addSerializationExclusionStrategy(underscoreExclusionStrategy); // Render KeywordCollection as an array of KeywordInfos. builder.registerTypeAdapter(KeywordCollection.class, new JsonSerializer<KeywordCollection>() { @Override public JsonElement serialize(KeywordCollection src, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) { JsonArray out = new JsonArray(); for (KeywordInfo info : src.getListSortedByScore()) { out.add(context.serialize(info)); } return out; } }); // Render Money as a primitive. builder.registerTypeAdapter(Money.class, new JsonSerializer<Money>() { @Override public JsonElement serialize(Money src, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) { JsonElement out = new JsonPrimitive(src.getMicroAmount() / 1000000); return out; } }); // Render Keyword in a simple way. builder.registerTypeAdapter(Keyword.class, new JsonSerializer<Keyword>() { @Override public JsonElement serialize(Keyword src, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) { JsonObject out = new JsonObject(); out.addProperty("text", src.getText()); out.addProperty("matchtype", src.getMatchType().toString()); return out; } }); // Render Throwable in a simple way (for all subclasses). builder.registerTypeHierarchyAdapter(Throwable.class, new JsonSerializer<Throwable>() { @Override public JsonElement serialize(Throwable src, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) { JsonObject out = new JsonObject(); out.addProperty("message", src.getMessage()); out.addProperty("type", src.getClass().getName()); JsonArray stack = new JsonArray(); for (StackTraceElement stackTraceElement : src.getStackTrace()) { JsonObject stackElem = new JsonObject(); stackElem.addProperty("file", stackTraceElement.getFileName()); stackElem.addProperty("line", stackTraceElement.getLineNumber()); stackElem.addProperty("method", stackTraceElement.getMethodName()); stackElem.addProperty("class", stackTraceElement.getClassName()); stack.add(stackElem); } out.add("stack", stack); if (src.getCause() != null) { out.add("cause", context.serialize(src.getCause())); } return out; } }); if (prettyPrint) { builder.setPrettyPrinting(); } return builder.create(); }