Search in sources :

Example 1 with JSONSerializer

use of org.jabsorb.JSONSerializer in project wonder-slim by undur.

the class AjaxUtils method arrayValueForObject.

/**
 * Returns the array for the given object.  If the object is a string, it will be parsed as a
 * JSON value.
 *
 * @param <T> the array type
 * @param value the object value
 * @return an array (or null)
 */
@SuppressWarnings("unchecked")
public static <T> NSArray<T> arrayValueForObject(Object value) {
    NSArray arrayValue;
    if (value == null) {
        arrayValue = null;
    } else if (value instanceof NSArray) {
        arrayValue = (NSArray<T>) value;
    } else if (value instanceof String) {
        try {
            String strValue = ((String) value).trim();
            if (!strValue.startsWith("[")) {
                strValue = "[" + strValue + "]";
            }
            JSONSerializer serializer = new JSONSerializer();
            serializer.registerDefaultSerializers();
            Object objValue = serializer.fromJSON(strValue);
            if (objValue.getClass().isArray()) {
                arrayValue = new NSArray((Object[]) objValue);
            } else if (objValue instanceof Collection) {
                arrayValue = new NSArray((Collection) objValue);
            } else {
                arrayValue = new NSArray(objValue);
            }
        } catch (Throwable e) {
            throw new IllegalArgumentException("Failed to convert String to array.", e);
        }
    } else {
        throw new IllegalArgumentException("Unable to convert '" + value + "' to an array.");
    }
    return arrayValue;
}
Also used : NSArray(com.webobjects.foundation.NSArray) Collection(java.util.Collection) JSONSerializer(org.jabsorb.JSONSerializer)

Example 2 with JSONSerializer

use of org.jabsorb.JSONSerializer in project wonder-slim by undur.

the class JavaJSONClient method create.

/**
 * Creates and returns a JSON Client.
 *
 * @param jsonUrl
 *            the JSON service URL
 * @param useHttpClient
 *            if true, Commons HTTPClient will be used instead of URLConnection (much better, but requires
 *            HttpClient)
 * @return the JSON client
 * @throws Exception
 *             if the client creation fails
 */
public static Client create(String jsonUrl, boolean useHttpClient) throws Exception {
    if (useHttpClient) {
        HTTPSession.register(TransportRegistry.i());
    }
    Client client = new Client(TransportRegistry.i().createSession(jsonUrl));
    Field serializerField = client.getClass().getDeclaredField("serializer");
    serializerField.setAccessible(true);
    JSONSerializer serializer = (JSONSerializer) serializerField.get(client);
    serializer.registerSerializer(new JSONEnterpriseObjectSerializer());
    serializer.registerSerializer(new NSArraySerializer());
    serializer.registerSerializer(new NSDictionarySerializer());
    serializer.registerSerializer(new NSTimestampSerializer());
    serializer.registerSerializer(new NSDataSerializer());
    return client;
}
Also used : Field(java.lang.reflect.Field) NSArraySerializer(er.ajax.json.serializer.NSArraySerializer) NSTimestampSerializer(er.ajax.json.serializer.NSTimestampSerializer) JSONEnterpriseObjectSerializer(er.ajax.json.serializer.JSONEnterpriseObjectSerializer) NSDataSerializer(er.ajax.json.serializer.NSDataSerializer) Client(org.jabsorb.client.Client) NSDictionarySerializer(er.ajax.json.serializer.NSDictionarySerializer) JSONSerializer(org.jabsorb.JSONSerializer)

Example 3 with JSONSerializer

use of org.jabsorb.JSONSerializer in project servoy-client by Servoy.

the class JSONSerializerWrapper method getSerializer.

protected synchronized JSONSerializer getSerializer() {
    if (serializer == null) {
        serializer = new JSONSerializer() {

            @Override
            public Object marshall(SerializerState state, Object parent, Object java, Object ref) throws MarshallException {
                // NativeArray may contain wrapped data
                return super.marshall(state, parent, wrapToJSON(java), ref);
            }

            @Override
            public Object unmarshall(SerializerState state, Class clazz, Object json) throws UnmarshallException {
                if ((clazz == null || clazz == Object.class) && json instanceof JSONObject && !((JSONObject) json).has("javaClass")) {
                    // NativeObjectSerializer when there is no class hint
                    clazz = NativeObject.class;
                }
                if (clazz == null && json instanceof JSONArray) {
                    // default native array when there is no class hint
                    clazz = NativeArray.class;
                }
                if ((clazz == null || clazz == Object.class) && json instanceof Boolean) {
                    // hack to make sure BooleanSerializer is used
                    clazz = Boolean.class;
                }
                return super.unmarshall(state, clazz, json);
            }

            @Override
            public boolean isPrimitive(Object o) {
                if (o != null) {
                    Class cls = o.getClass();
                    if (cls == java.math.BigDecimal.class || cls == java.math.BigInteger.class) {
                        return true;
                    }
                }
                return super.isPrimitive(o);
            }

            @Override
            protected Class getClassFromHint(Object o) throws UnmarshallException {
                if (o == null) {
                    return null;
                }
                if (o instanceof JSONObject) {
                    String className = "(unknown)";
                    try {
                        className = ((JSONObject) o).getString("javaClass");
                        return Class.forName(className);
                    } catch (Exception e) {
                        throw new UnmarshallException("Class specified in javaClass hint not found: " + className, e);
                    }
                }
                if (o instanceof JSONArray) {
                    JSONArray arr = (JSONArray) o;
                    if (arr.length() == 0) {
                        // assume Object array (best guess)
                        return Object[].class;
                    }
                    // return type of first element
                    Class compClazz;
                    try {
                        compClazz = getClassFromHint(arr.get(0));
                    } catch (JSONException e) {
                        throw (NoSuchElementException) new NoSuchElementException(e.getMessage()).initCause(e);
                    }
                    try {
                        if (compClazz.isArray()) {
                            return Class.forName("[" + compClazz.getName());
                        }
                        return Class.forName("[L" + compClazz.getName() + ";");
                    } catch (ClassNotFoundException e) {
                        throw new UnmarshallException("problem getting array type", e);
                    }
                }
                return o.getClass();
            }
        };
        try {
            serializer.setFixupDuplicates(false);
            // registerDefaultSerializers
            // least-specific serializers first, they will be selected last if no other serializer matches
            serializer.registerSerializer(new BeanSerializer());
            serializer.registerSerializer(new RawJSONArraySerializer() {

                @Override
                public boolean canSerialize(Class clazz, Class jsonClazz) {
                    // make sure JSONArray subclasses are also serialized as just the json
                    return JSONArray.class.isAssignableFrom(clazz) && (jsonClazz == null || jsonClazz == JSONArray.class);
                }
            });
            serializer.registerSerializer(new RawJSONObjectSerializer() {

                @Override
                public boolean canSerialize(Class clazz, Class jsonClazz) {
                    // make sure JSONObject subclasses are also serialized as just the json
                    return JSONObject.class.isAssignableFrom(clazz) && (jsonClazz == null || jsonClazz == JSONObject.class);
                }
            });
            serializer.registerSerializer(new ArraySerializer());
            serializer.registerSerializer(new DictionarySerializer());
            serializer.registerSerializer(new MapSerializer());
            serializer.registerSerializer(new SetSerializer());
            serializer.registerSerializer(new ListSerializer());
            serializer.registerSerializer(new ServoyDateSerializer());
            // handle byte arrays as base64 encoded?
            serializer.registerSerializer(handleByteArrays ? new StringByteArraySerializer() : new StringSerializer());
            serializer.registerSerializer(new NumberSerializer());
            serializer.registerSerializer(new BooleanSerializer());
            serializer.registerSerializer(new PrimitiveSerializer());
            serializer.registerSerializer(new QueryBuilderSerializer(this));
            serializer.registerSerializer(new NativeObjectSerializer());
            serializer.registerSerializer(new NullForUndefinedSerializer());
        } catch (Exception e) {
            Debug.error(e);
        }
    }
    return serializer;
}
Also used : NativeArray(org.mozilla.javascript.NativeArray) ListSerializer(org.jabsorb.serializer.impl.ListSerializer) ArraySerializer(org.jabsorb.serializer.impl.ArraySerializer) RawJSONArraySerializer(org.jabsorb.serializer.impl.RawJSONArraySerializer) BooleanSerializer(org.jabsorb.serializer.impl.BooleanSerializer) MapSerializer(org.jabsorb.serializer.impl.MapSerializer) StringSerializer(org.jabsorb.serializer.impl.StringSerializer) JSONSerializer(org.jabsorb.JSONSerializer) BeanSerializer(org.jabsorb.serializer.impl.BeanSerializer) DictionarySerializer(org.jabsorb.serializer.impl.DictionarySerializer) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) SetSerializer(org.jabsorb.serializer.impl.SetSerializer) RawJSONArraySerializer(org.jabsorb.serializer.impl.RawJSONArraySerializer) JSONException(org.json.JSONException) NoSuchElementException(java.util.NoSuchElementException) UnmarshallException(org.jabsorb.serializer.UnmarshallException) MarshallException(org.jabsorb.serializer.MarshallException) NativeObject(org.mozilla.javascript.NativeObject) NumberSerializer(org.jabsorb.serializer.impl.NumberSerializer) JSONObject(org.json.JSONObject) MarshallException(org.jabsorb.serializer.MarshallException) NativeObject(org.mozilla.javascript.NativeObject) JSONObject(org.json.JSONObject) PrimitiveSerializer(org.jabsorb.serializer.impl.PrimitiveSerializer) SerializerState(org.jabsorb.serializer.SerializerState) UnmarshallException(org.jabsorb.serializer.UnmarshallException) NoSuchElementException(java.util.NoSuchElementException) RawJSONObjectSerializer(org.jabsorb.serializer.impl.RawJSONObjectSerializer)

Example 4 with JSONSerializer

use of org.jabsorb.JSONSerializer in project servoy-client by Servoy.

the class XMLUtils method parseColumnTypeArray.

/**
 * Parse an array string '[[tp,len,scale], [tp,len,scale], ...]' as ColumnType list
 */
public static List<ColumnType> parseColumnTypeArray(String s) {
    if (s == null)
        return null;
    List<ColumnType> list = null;
    JSONSerializer serializer = new JSONSerializer();
    try {
        serializer.registerDefaultSerializers();
        Integer[][] array = (Integer[][]) serializer.fromJSON(s);
        if (array != null && array.length > 0) {
            list = new ArrayList<ColumnType>(array.length);
            for (Integer[] elem : array) {
                list.add(ColumnType.getInstance(elem[0].intValue(), elem[1].intValue(), elem[2].intValue()));
            }
        }
    } catch (Exception e) {
        Debug.error(e);
    }
    return list;
}
Also used : ColumnType(com.servoy.j2db.query.ColumnType) BaseColumnType(com.servoy.base.query.BaseColumnType) SAXParseException(org.xml.sax.SAXParseException) SAXException(org.xml.sax.SAXException) RepositoryException(com.servoy.j2db.persistence.RepositoryException) JSONSerializer(org.jabsorb.JSONSerializer)

Aggregations

JSONSerializer (org.jabsorb.JSONSerializer)4 BaseColumnType (com.servoy.base.query.BaseColumnType)1 RepositoryException (com.servoy.j2db.persistence.RepositoryException)1 ColumnType (com.servoy.j2db.query.ColumnType)1 NSArray (com.webobjects.foundation.NSArray)1 JSONEnterpriseObjectSerializer (er.ajax.json.serializer.JSONEnterpriseObjectSerializer)1 NSArraySerializer (er.ajax.json.serializer.NSArraySerializer)1 NSDataSerializer (er.ajax.json.serializer.NSDataSerializer)1 NSDictionarySerializer (er.ajax.json.serializer.NSDictionarySerializer)1 NSTimestampSerializer (er.ajax.json.serializer.NSTimestampSerializer)1 Field (java.lang.reflect.Field)1 Collection (java.util.Collection)1 NoSuchElementException (java.util.NoSuchElementException)1 Client (org.jabsorb.client.Client)1 MarshallException (org.jabsorb.serializer.MarshallException)1 SerializerState (org.jabsorb.serializer.SerializerState)1 UnmarshallException (org.jabsorb.serializer.UnmarshallException)1 ArraySerializer (org.jabsorb.serializer.impl.ArraySerializer)1 BeanSerializer (org.jabsorb.serializer.impl.BeanSerializer)1 BooleanSerializer (org.jabsorb.serializer.impl.BooleanSerializer)1