Search in sources :

Example 6 with JsonArray

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);
    }
}
Also used : JsonArray(com.helger.json.JsonArray) IJsonArray(com.helger.json.IJsonArray) IJsonObject(com.helger.json.IJsonObject) IJsonObject(com.helger.json.IJsonObject) JsonObject(com.helger.json.JsonObject) IJsonArray(com.helger.json.IJsonArray) ICommonsOrderedMap(com.helger.commons.collection.impl.ICommonsOrderedMap) Map(java.util.Map) CommonsLinkedHashMap(com.helger.commons.collection.impl.CommonsLinkedHashMap)

Example 7 with JsonArray

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"))));
}
Also used : JsonArray(com.helger.json.JsonArray) JsonObject(com.helger.json.JsonObject) Test(org.junit.Test)

Example 8 with JsonArray

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&lt;?&gt; - recursive invocation</li>
 * <li>Map&lt;?,?&gt; - 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);
}
Also used : IJsonObject(com.helger.json.IJsonObject) JsonObject(com.helger.json.JsonObject) IHasJson(com.helger.json.IHasJson) JsonArray(com.helger.json.JsonArray) IJsonArray(com.helger.json.IJsonArray) IJsonObject(com.helger.json.IJsonObject) IJson(com.helger.json.IJson) Collection(java.util.Collection) IJsonObject(com.helger.json.IJsonObject) JsonObject(com.helger.json.JsonObject) IJsonArray(com.helger.json.IJsonArray) Map(java.util.Map) Nonnull(javax.annotation.Nonnull)

Example 9 with JsonArray

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);
    }
}
Also used : Locale(java.util.Locale) Serializable(java.io.Serializable) WrappedCollectingValidationEventHandler(com.helger.jaxb.validation.WrappedCollectingValidationEventHandler) IJsonObject(com.helger.json.IJsonObject) JsonObject(com.helger.json.JsonObject) IError(com.helger.commons.error.IError) JsonWriter(com.helger.json.serialize.JsonWriter) CreditNoteType(oasis.names.specification.ubl.schema.xsd.creditnote_21.CreditNoteType) StopWatch(com.helger.commons.timing.StopWatch) CrossIndustryInvoiceType(un.unece.uncefact.data.standard.crossindustryinvoice._100.CrossIndustryInvoiceType) InvoiceType(oasis.names.specification.ubl.schema.xsd.invoice_21.InvoiceType) JsonArray(com.helger.json.JsonArray) IJsonArray(com.helger.json.IJsonArray) ErrorList(com.helger.commons.error.list.ErrorList) ZonedDateTime(java.time.ZonedDateTime) IJsonObject(com.helger.json.IJsonObject) IJsonArray(com.helger.json.IJsonArray) CIIToUBL21Converter(com.helger.en16931.cii2ubl.CIIToUBL21Converter) CrossIndustryInvoiceType(un.unece.uncefact.data.standard.crossindustryinvoice._100.CrossIndustryInvoiceType)

Example 10 with JsonArray

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;
}
Also used : JsonArray(com.helger.json.JsonArray) Nonnegative(javax.annotation.Nonnegative) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) SimpleDocumentTypeIdentifier(com.helger.peppolid.simple.doctype.SimpleDocumentTypeIdentifier) IHasJson(com.helger.json.IHasJson) PDBusinessCard(com.helger.pd.businesscard.generic.PDBusinessCard) IDocumentTypeIdentifier(com.helger.peppolid.IDocumentTypeIdentifier) Predicate(java.util.function.Predicate) IJsonObject(com.helger.json.IJsonObject) ToStringGenerator(com.helger.commons.string.ToStringGenerator) JsonObject(com.helger.json.JsonObject) Serializable(java.io.Serializable) ValueEnforcer(com.helger.commons.ValueEnforcer) JsonArray(com.helger.json.JsonArray) PDIdentifier(com.helger.pd.businesscard.generic.PDIdentifier) ICommonsList(com.helger.commons.collection.impl.ICommonsList) IJson(com.helger.json.IJson) ReturnsMutableObject(com.helger.commons.annotation.ReturnsMutableObject) ReturnsMutableCopy(com.helger.commons.annotation.ReturnsMutableCopy) Nonnull(javax.annotation.Nonnull) Immutable(javax.annotation.concurrent.Immutable) Nullable(javax.annotation.Nullable) IJsonObject(com.helger.json.IJsonObject) IJsonObject(com.helger.json.IJsonObject) JsonObject(com.helger.json.JsonObject) Nonnull(javax.annotation.Nonnull)

Aggregations

JsonArray (com.helger.json.JsonArray)20 JsonObject (com.helger.json.JsonObject)20 IJsonObject (com.helger.json.IJsonObject)19 IJsonArray (com.helger.json.IJsonArray)16 Nonnull (javax.annotation.Nonnull)13 Map (java.util.Map)6 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)3 ICommonsList (com.helger.commons.collection.impl.ICommonsList)3 ICommonsMap (com.helger.commons.collection.impl.ICommonsMap)3 IError (com.helger.commons.error.IError)3 IDocumentTypeIdentifier (com.helger.peppolid.IDocumentTypeIdentifier)3 IParticipantIdentifier (com.helger.peppolid.IParticipantIdentifier)3 ZonedDateTime (java.time.ZonedDateTime)3 Query (org.apache.lucene.search.Query)3 Nonempty (com.helger.commons.annotation.Nonempty)2 CommonsTreeSet (com.helger.commons.collection.impl.CommonsTreeSet)2 StopWatch (com.helger.commons.timing.StopWatch)2 IHasJson (com.helger.json.IHasJson)2 IJson (com.helger.json.IJson)2 JsonWriter (com.helger.json.serialize.JsonWriter)2