Search in sources :

Example 1 with JsonObjectBuilder

use of jakarta.json.JsonObjectBuilder in project JsonPath by json-path.

the class JakartaMappingProvider method mapImpl.

private Object mapImpl(Object source, final Type targetType) {
    if (source == null || source == JsonValue.NULL) {
        return null;
    }
    if (source == JsonValue.TRUE) {
        if (Boolean.class.equals(targetType)) {
            return Boolean.TRUE;
        } else {
            String className = targetType.toString();
            throw new MappingException("JSON boolean (true) cannot be mapped to " + className);
        }
    }
    if (source == JsonValue.FALSE) {
        if (Boolean.class.equals(targetType)) {
            return Boolean.FALSE;
        } else {
            String className = targetType.toString();
            throw new MappingException("JSON boolean (false) cannot be mapped to " + className);
        }
    } else if (source instanceof JsonString) {
        if (String.class.equals(targetType)) {
            return ((JsonString) source).getChars();
        } else {
            String className = targetType.toString();
            throw new MappingException("JSON string cannot be mapped to " + className);
        }
    } else if (source instanceof JsonNumber) {
        JsonNumber jsonNumber = (JsonNumber) source;
        if (jsonNumber.isIntegral()) {
            return mapIntegralJsonNumber(jsonNumber, getRawClass(targetType));
        } else {
            return mapDecimalJsonNumber(jsonNumber, getRawClass(targetType));
        }
    }
    if (source instanceof JsonArrayBuilder) {
        source = ((JsonArrayBuilder) source).build();
    } else if (source instanceof JsonObjectBuilder) {
        source = ((JsonObjectBuilder) source).build();
    }
    if (source instanceof Collection) {
        // this covers both List<JsonValue> and JsonArray from JSON-P spec
        Class<?> rawTargetType = getRawClass(targetType);
        Type targetTypeArg = getFirstTypeArgument(targetType);
        Collection<Object> result = newCollectionOfType(rawTargetType);
        for (Object srcValue : (Collection<?>) source) {
            if (srcValue instanceof JsonObject) {
                if (targetTypeArg != null) {
                    result.add(mapImpl(srcValue, targetTypeArg));
                } else {
                    result.add(srcValue);
                }
            } else {
                result.add(unwrapJsonValue(srcValue));
            }
        }
        return result;
    } else if (source instanceof JsonObject) {
        if (targetType instanceof Class) {
            if (jsonToClassMethod != null) {
                try {
                    JsonParser jsonParser = new JsonStructureToParserAdapter((JsonStructure) source);
                    return jsonToClassMethod.invoke(jsonb, jsonParser, (Class<?>) targetType);
                } catch (Exception e) {
                    throw new MappingException(e);
                }
            } else {
                try {
                    // Fallback databinding approach for JSON-B API implementations without
                    // explicit support for use of JsonParser in their public API. The approach
                    // is essentially first to serialize given value into JSON, and then bind
                    // it to data object of given class.
                    String json = source.toString();
                    return jsonb.fromJson(json, (Class<?>) targetType);
                } catch (JsonbException e) {
                    throw new MappingException(e);
                }
            }
        } else if (targetType instanceof ParameterizedType) {
            if (jsonToTypeMethod != null) {
                try {
                    JsonParser jsonParser = new JsonStructureToParserAdapter((JsonStructure) source);
                    return jsonToTypeMethod.invoke(jsonb, jsonParser, (Type) targetType);
                } catch (Exception e) {
                    throw new MappingException(e);
                }
            } else {
                try {
                    // Fallback databinding approach for JSON-B API implementations without
                    // explicit support for use of JsonParser in their public API. The approach
                    // is essentially first to serialize given value into JSON, and then bind
                    // the JSON string to data object of given type.
                    String json = source.toString();
                    return jsonb.fromJson(json, (Type) targetType);
                } catch (JsonbException e) {
                    throw new MappingException(e);
                }
            }
        } else {
            throw new MappingException("JSON object cannot be databind to " + targetType);
        }
    } else {
        return source;
    }
}
Also used : JsonObject(jakarta.json.JsonObject) JsonString(jakarta.json.JsonString) JsonbException(jakarta.json.bind.JsonbException) JsonException(jakarta.json.JsonException) NoSuchElementException(java.util.NoSuchElementException) ParameterizedType(java.lang.reflect.ParameterizedType) GenericArrayType(java.lang.reflect.GenericArrayType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) JsonNumber(jakarta.json.JsonNumber) JsonbException(jakarta.json.bind.JsonbException) Collection(java.util.Collection) JsonObject(jakarta.json.JsonObject) JsonString(jakarta.json.JsonString) JsonArrayBuilder(jakarta.json.JsonArrayBuilder) JsonObjectBuilder(jakarta.json.JsonObjectBuilder) JsonParser(jakarta.json.stream.JsonParser) JsonStructure(jakarta.json.JsonStructure)

Example 2 with JsonObjectBuilder

use of jakarta.json.JsonObjectBuilder in project dash-licenses by eclipse.

the class EclipseFoundationSupport method buildRequestPayload.

private JsonObject buildRequestPayload(Collection<IContentId> ids) {
    JsonObjectBuilder request = Json.createObjectBuilder();
    var projectId = settings.getProjectId();
    if (projectId != null) {
        logger.debug("Querying for project {}.", projectId);
        request.add("project", projectId);
    }
    JsonArrayBuilder builder = Json.createBuilderFactory(null).createArrayBuilder();
    ids.stream().forEach(id -> builder.add(id.toString()));
    request.add("dependencies", builder);
    return request.build();
}
Also used : JsonArrayBuilder(jakarta.json.JsonArrayBuilder) JsonObjectBuilder(jakarta.json.JsonObjectBuilder)

Example 3 with JsonObjectBuilder

use of jakarta.json.JsonObjectBuilder in project opensearch-java by opensearch-project.

the class JsonValueParser method parseObject.

public JsonObject parseObject(JsonParser parser) throws IOException {
    JsonObjectBuilder ob = provider.createObjectBuilder();
    JsonToken token;
    while ((token = parser.nextToken()) != JsonToken.END_OBJECT) {
        if (token != JsonToken.FIELD_NAME) {
            throw new JsonParsingException("Expected a property name", new JacksonJsonpLocation(parser));
        }
        String name = parser.getCurrentName();
        parser.nextToken();
        ob.add(name, parseValue(parser));
    }
    return ob.build();
}
Also used : JsonToken(com.fasterxml.jackson.core.JsonToken) JsonObjectBuilder(jakarta.json.JsonObjectBuilder) JsonParsingException(jakarta.json.stream.JsonParsingException)

Example 4 with JsonObjectBuilder

use of jakarta.json.JsonObjectBuilder in project glassfish-hk2 by eclipse-ee4j.

the class JsonParser method marshal.

/* (non-Javadoc)
     * @see org.glassfish.hk2.xml.spi.XmlServiceParser#marshall(java.io.OutputStream, org.glassfish.hk2.xml.api.XmlRootHandle)
     */
@Override
public <T> void marshal(OutputStream outputStream, XmlRootHandle<T> rootHandle, Map<String, Object> options) throws IOException {
    JsonObjectBuilder objectBuilder = Json.createObjectBuilder();
    T root = rootHandle.getRoot();
    JsonObject rootObject = createJsonObject((BaseHK2JAXBBean) root, objectBuilder);
    Map<String, Object> config = new HashMap<String, Object>();
    config.put(JsonGenerator.PRETTY_PRINTING, Boolean.TRUE);
    JsonWriterFactory writerFactory = Json.createWriterFactory(config);
    JsonWriter writer = writerFactory.createWriter(outputStream);
    try {
        writer.writeObject(rootObject);
    } finally {
        writer.close();
    }
}
Also used : HashMap(java.util.HashMap) JsonObject(jakarta.json.JsonObject) JsonObject(jakarta.json.JsonObject) JsonObjectBuilder(jakarta.json.JsonObjectBuilder) JsonWriter(jakarta.json.JsonWriter) JsonWriterFactory(jakarta.json.JsonWriterFactory)

Example 5 with JsonObjectBuilder

use of jakarta.json.JsonObjectBuilder in project glassfish-hk2 by eclipse-ee4j.

the class JsonParser method createJsonObject.

@SuppressWarnings("unchecked")
private JsonObject createJsonObject(BaseHK2JAXBBean bean, JsonObjectBuilder builder) {
    if (bean == null) {
        return builder.build();
    }
    ModelImpl model = bean._getModel();
    Map<QName, ChildDescriptor> allChildren = model.getAllChildrenDescriptors();
    for (Map.Entry<QName, ChildDescriptor> entry : allChildren.entrySet()) {
        QName keyNameQName = entry.getKey();
        String keyName = keyNameQName.getLocalPart();
        if (!bean._isSet(keyName))
            continue;
        Object value = bean._getProperty(XmlService.DEFAULT_NAMESPACE, keyName);
        ParentedModel parented = entry.getValue().getParentedModel();
        if (parented != null) {
            if (ChildType.DIRECT.equals(parented.getChildType())) {
                if (value != null) {
                    builder = builder.add(keyName, createJsonObject((BaseHK2JAXBBean) value, Json.createObjectBuilder()));
                }
            } else if (ChildType.LIST.equals(parented.getChildType())) {
                List<BaseHK2JAXBBean> list = (List<BaseHK2JAXBBean>) value;
                if (list != null && !list.isEmpty()) {
                    JsonArrayBuilder jsonArray = Json.createArrayBuilder();
                    for (BaseHK2JAXBBean item : list) {
                        JsonObjectBuilder childBuilder = Json.createObjectBuilder();
                        JsonObject obj = createJsonObject(item, childBuilder);
                        jsonArray.add(obj);
                    }
                    builder.add(keyName, jsonArray);
                }
            } else if (ChildType.ARRAY.equals(parented.getChildType())) {
                int length = Array.getLength(value);
                if (length > 0) {
                    JsonArrayBuilder jsonArray = Json.createArrayBuilder();
                    for (int lcv = 0; lcv < length; lcv++) {
                        BaseHK2JAXBBean item = (BaseHK2JAXBBean) Array.get(value, lcv);
                        JsonObjectBuilder childBuilder = Json.createObjectBuilder();
                        JsonObject obj = createJsonObject(item, childBuilder);
                        jsonArray.add(obj);
                    }
                    builder.add(keyName, jsonArray);
                }
            } else {
                throw new AssertionError("Unknown childType " + parented.getChildType());
            }
        } else {
            if (value == null) {
                builder.addNull(keyName);
            } else if (value instanceof Integer) {
                builder.add(keyName, ((Integer) value).intValue());
            } else if (value instanceof Long) {
                builder.add(keyName, ((Long) value).longValue());
            } else if (value instanceof Boolean) {
                builder.add(keyName, ((Boolean) value).booleanValue());
            } else {
                builder.add(keyName, value.toString());
            }
        }
    }
    return builder.build();
}
Also used : QName(javax.xml.namespace.QName) ChildDescriptor(org.glassfish.hk2.xml.internal.ChildDescriptor) JsonObject(jakarta.json.JsonObject) ParentedModel(org.glassfish.hk2.xml.internal.ParentedModel) BaseHK2JAXBBean(org.glassfish.hk2.xml.jaxb.internal.BaseHK2JAXBBean) JsonObject(jakarta.json.JsonObject) LinkedList(java.util.LinkedList) List(java.util.List) JsonArrayBuilder(jakarta.json.JsonArrayBuilder) ModelImpl(org.glassfish.hk2.xml.internal.ModelImpl) JsonObjectBuilder(jakarta.json.JsonObjectBuilder) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

JsonObjectBuilder (jakarta.json.JsonObjectBuilder)8 JsonObject (jakarta.json.JsonObject)6 JsonArrayBuilder (jakarta.json.JsonArrayBuilder)4 JsonString (jakarta.json.JsonString)3 JsonException (jakarta.json.JsonException)2 JsonNumber (jakarta.json.JsonNumber)2 JsonStructure (jakarta.json.JsonStructure)2 JsonWriter (jakarta.json.JsonWriter)2 JsonbException (jakarta.json.bind.JsonbException)2 JsonParser (jakarta.json.stream.JsonParser)2 GenericArrayType (java.lang.reflect.GenericArrayType)2 ParameterizedType (java.lang.reflect.ParameterizedType)2 Type (java.lang.reflect.Type)2 Collection (java.util.Collection)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 NoSuchElementException (java.util.NoSuchElementException)2 JsonToken (com.fasterxml.jackson.core.JsonToken)1 BASE64Encoder (com.sun.messaging.jmq.util.BASE64Encoder)1 JsonBuilderFactory (jakarta.json.JsonBuilderFactory)1