use of com.helger.json.JsonArray in project phase4 by phax.
the class PModeJsonConverter method setObjectFields.
public static void setObjectFields(@Nonnull final IBusinessObject aValue, @Nonnull final IJsonObject aElement) {
aElement.add(ATTR_ID, aValue.getID());
if (aValue.hasCreationDateTime())
aElement.add(ATTR_CREATIONLDT, PDTWebDateHelper.getAsStringXSD(aValue.getCreationDateTime()));
if (aValue.hasCreationUserID())
aElement.add(ATTR_CREATIONUSERID, aValue.getCreationUserID());
if (aValue.hasLastModificationDateTime())
aElement.add(ATTR_LASTMODLDT, PDTWebDateHelper.getAsStringXSD(aValue.getLastModificationDateTime()));
if (aValue.hasLastModificationUserID())
aElement.add(ATTR_LASTMODUSERID, aValue.getLastModificationUserID());
if (aValue.hasDeletionDateTime())
aElement.add(ATTR_DELETIONLDT, PDTWebDateHelper.getAsStringXSD(aValue.getDeletionDateTime()));
if (aValue.hasDeletionUserID())
aElement.add(ATTR_DELETIONUSERID, aValue.getDeletionUserID());
if (aValue.attrs().isNotEmpty()) {
final IJsonArray aCustomArray = new JsonArray();
for (final Map.Entry<String, String> aEntry : CollectionHelper.getSortedByKey(aValue.attrs()).entrySet()) {
final IJsonObject eCustom = new JsonObject();
eCustom.add(ATTR_ID, aEntry.getKey());
if (aEntry.getValue() != null)
eCustom.add(VALUE, aEntry.getValue());
aCustomArray.add(eCustom);
}
aElement.addJson(ELEMENT_CUSTOM, aCustomArray);
}
}
use of com.helger.json.JsonArray in project ph-commons by phax.
the class JsonWriterTest method testIndent.
@Test
public void testIndent() {
final String sCRLF = JsonWriterSettings.DEFAULT_NEWLINE_STRING;
final JsonWriter aWriter = new JsonWriter(JsonWriterSettings.DEFAULT_SETTINGS_FORMATTED);
assertEquals("{}", aWriter.writeAsString(new JsonObject()));
assertEquals("{" + sCRLF + " \"foo\":\"bar\"" + sCRLF + "}", aWriter.writeAsString(new JsonObject().add("foo", "bar")));
assertEquals("{" + sCRLF + " \"foo\":[" + sCRLF + " 1," + sCRLF + " 2" + sCRLF + " ]" + sCRLF + "}", aWriter.writeAsString(new JsonObject().addJson("foo", new JsonArray().add(1).add(2))));
assertEquals("{" + sCRLF + " \"foo\":{" + sCRLF + " \"bar\":\"baz\"" + sCRLF + " }" + sCRLF + "}", aWriter.writeAsString(new JsonObject().addJson("foo", new JsonObject().add("bar", "baz"))));
assertEquals("[]", aWriter.writeAsString(new JsonArray()));
assertEquals("[" + sCRLF + " {" + sCRLF + " \"foo\":\"bar\"" + sCRLF + " }" + sCRLF + "]", aWriter.writeAsString(new JsonArray().add(new JsonObject().add("foo", "bar"))));
}
use of com.helger.json.JsonArray in project ph-commons by phax.
the class JsonConverter method convertToJson.
/**
* Convert any Object to an {@link IJson} representation. Supported classes
* are:
* <ul>
* <li><code>null</code></li>
* <li>com.helger.json.IJson</li>
* <li>com.helger.json.IJsonProvider</li>
* <li>boolean []</li>
* <li>byte []</li>
* <li>char []</li>
* <li>double []</li>
* <li>float []</li>
* <li>int []</li>
* <li>long []</li>
* <li>short []</li>
* <li>Object [] - recursive invocation</li>
* <li>Collection<?> - recursive invocation</li>
* <li>Map<?,?> - recursive invocation, key must be a String!</li>
* </ul>
* All other objects are put "as is" into {@link JsonValue} objects.
*
* @param aObject
* Source Object to convert May be <code>null</code>.
* @return Never <code>null</code>.
*/
@Nonnull
public static IJson convertToJson(@Nullable final Object aObject) {
if (aObject == null)
return JsonValue.NULL;
if (aObject instanceof IJson)
return (IJson) aObject;
if (aObject instanceof IHasJson)
return ((IHasJson) aObject).getAsJson();
if (ArrayHelper.isArray(aObject)) {
if (aObject instanceof boolean[]) {
final boolean[] aArray = (boolean[]) aObject;
return new JsonArray(aArray.length).addAll(aArray);
}
if (aObject instanceof byte[]) {
final byte[] aArray = (byte[]) aObject;
return new JsonArray(aArray.length).addAll(aArray);
}
if (aObject instanceof char[]) {
final char[] aArray = (char[]) aObject;
return new JsonArray(aArray.length).addAll(aArray);
}
if (aObject instanceof double[]) {
final double[] aArray = (double[]) aObject;
return new JsonArray(aArray.length).addAll(aArray);
}
if (aObject instanceof float[]) {
final float[] aArray = (float[]) aObject;
return new JsonArray(aArray.length).addAll(aArray);
}
if (aObject instanceof int[]) {
final int[] aArray = (int[]) aObject;
return new JsonArray(aArray.length).addAll(aArray);
}
if (aObject instanceof long[]) {
final long[] aArray = (long[]) aObject;
return new JsonArray(aArray.length).addAll(aArray);
}
if (aObject instanceof short[]) {
final short[] aArray = (short[]) aObject;
return new JsonArray(aArray.length).addAll(aArray);
}
if (aObject instanceof Object[]) {
final Object[] aArray = (Object[]) aObject;
final IJsonArray aJsonArray = new JsonArray(aArray.length);
for (final Object aValue : aArray) {
// Recursive conversion
aJsonArray.add(convertToJson(aValue));
}
return aJsonArray;
}
throw new IllegalStateException("Expected an array but got none. Object=" + aObject);
}
if (aObject instanceof Collection<?>) {
final Collection<?> aCollection = (Collection<?>) aObject;
final IJsonArray aJsonArray = new JsonArray(aCollection.size());
for (final Object aValue : aCollection) {
// Recursive conversion
aJsonArray.add(convertToJson(aValue));
}
return aJsonArray;
}
if (aObject instanceof Map<?, ?>) {
final Map<?, ?> aMap = (Map<?, ?>) aObject;
final IJsonObject aJsonObject = new JsonObject(aMap.size());
for (final Map.Entry<?, ?> aEntry : aMap.entrySet()) {
final String sKey = TypeConverter.convert(aEntry.getKey(), String.class);
if (sKey == null)
throw new IllegalArgumentException("Map key '" + aEntry.getKey() + "' could not be converted to a String!");
// Recursive conversion
final IJson aValue = convertToJson(aEntry.getValue());
aJsonObject.addJson(sKey, aValue);
}
return aJsonObject;
}
// Assume it is a simple value
return JsonValue.create(aObject);
}
use of com.helger.json.JsonArray in project peppol-practical by phax.
the class APIConvertCIIToUBL method rateLimitedInvokeAPI.
@Override
protected void rateLimitedInvokeAPI(@Nonnull final IAPIDescriptor aAPIDescriptor, @Nonnull @Nonempty final String sPath, @Nonnull final Map<String, String> aPathVariables, @Nonnull final IRequestWebScopeWithoutResponse aRequestScope, @Nonnull final UnifiedResponse aUnifiedResponse) throws Exception {
final ErrorList aErrorList = new ErrorList();
final Locale aDisplayLocale = CPPApp.DEFAULT_LOCALE;
final ZonedDateTime aQueryDT = PDTFactory.getCurrentZonedDateTimeUTC();
final StopWatch aSW = StopWatch.createdStarted();
// Params
final boolean bSimpleResponse = aRequestScope.params().getAsBoolean(PARAM_SIMPLE_RESPONSE, DEFAULT_SIMPLE_RESPONSE);
final boolean bXMLBeautify = aRequestScope.params().getAsBoolean(PARAM_XML_BEAUTIFY, DEFAULT_XML_BEAUTIFY);
final String sLogPrefix = "[API] ";
final IJsonObject aJson = new JsonObject();
aJson.add("conversionDateTime", DateTimeFormatter.ISO_ZONED_DATE_TIME.format(aQueryDT));
// Parse XML
LOGGER.info(sLogPrefix + "Parsing CII");
final CrossIndustryInvoiceType aCIIInvoice = CIID16BReader.crossIndustryInvoice().setValidationEventHandler(new WrappedCollectingValidationEventHandler(aErrorList)).read(aRequestScope.getRequest().getInputStream());
final long nParsingMillis = aSW.stopAndGetMillis();
aJson.add("parsingDuractionMillis", nParsingMillis);
{
final IJsonArray aParseErrors = new JsonArray();
for (final IError aError : aErrorList.getAllFailures()) aParseErrors.add(createItem(aError, aDisplayLocale));
aJson.addJson("parsingErrors", aParseErrors);
}
String sUBL = null;
boolean bSuccess = false;
if (aCIIInvoice != null) {
// Convert to domain model
LOGGER.info(sLogPrefix + "Converting CII to UBL with v" + CIIToUBLVersion.BUILD_VERSION + " (from " + CIIToUBLVersion.BUILD_TIMESTAMP + ")");
aSW.restart();
aErrorList.clear();
// Added since v1.3.0
aJson.add("conversionVersion", CIIToUBLVersion.BUILD_VERSION);
aJson.add("conversionBuildTimestamp", CIIToUBLVersion.BUILD_TIMESTAMP);
final Serializable aUBL = new CIIToUBL21Converter().setUBLCreationMode(EUBLCreationMode.AUTOMATIC).convertCIItoUBL(aCIIInvoice, aErrorList);
final long nConversionMillis = aSW.stopAndGetMillis();
aJson.add("conversionDuractionMillis", nConversionMillis);
{
final IJsonArray aConversionErrors = new JsonArray();
for (final IError aError : aErrorList.getAllFailures()) aConversionErrors.add(createItem(aError, aDisplayLocale));
aJson.addJson("coversionErrors", aConversionErrors);
}
if (aUBL != null) {
if (aUBL instanceof InvoiceType)
sUBL = UBL21Writer.invoice().setFormattedOutput(bXMLBeautify).getAsString((InvoiceType) aUBL);
else if (aUBL instanceof CreditNoteType)
sUBL = UBL21Writer.creditNote().setFormattedOutput(bXMLBeautify).getAsString((CreditNoteType) aUBL);
else
throw new IllegalStateException("Whaaaatttt");
aJson.add("ubl", sUBL);
bSuccess = true;
}
}
if (bSuccess)
LOGGER.info(sLogPrefix + "Successfully finished conversion");
else
LOGGER.info(sLogPrefix + "Finished conversion with errors");
if (bSimpleResponse && bSuccess) {
aUnifiedResponse.setContentAndCharset(sUBL, StandardCharsets.UTF_8).setMimeType(CMimeType.APPLICATION_XML);
} else {
if (!bSuccess)
aUnifiedResponse.setStatus(CHttp.HTTP_BAD_REQUEST).setAllowContentOnStatusCode(true);
final String sRet = new JsonWriter(JsonWriterSettings.DEFAULT_SETTINGS_FORMATTED).writeAsString(aJson);
aUnifiedResponse.setContentAndCharset(sRet, StandardCharsets.UTF_8).setMimeType(CMimeType.APPLICATION_JSON);
}
}
use of com.helger.json.JsonArray in project phoss-directory by phax.
the class PDExtendedBusinessCard method getAsJson.
@Nonnull
public IJsonObject getAsJson() {
final IJsonObject ret = new JsonObject();
ret.addJson("businesscard", m_aBusinessCard.getAsJson());
ret.addJson("doctypes", new JsonArray().addAllMapped(m_aDocumentTypeIDs, x -> PDIdentifier.getAsJson(x.getScheme(), x.getValue())));
return ret;
}
Aggregations