Example usage for com.badlogic.gdx.utils JsonValue child

List of usage examples for com.badlogic.gdx.utils JsonValue child

Introduction

In this page you can find the example usage for com.badlogic.gdx.utils JsonValue child.

Prototype

JsonValue child

To view the source code for com.badlogic.gdx.utils JsonValue child.

Click Source Link

Document

May be null.

Usage

From source file:be.ac.ucl.lfsab1509.bouboule.game.physicEditor.BodyEditorLoader.java

License:Open Source License

private RigidBodyModel readRigidBody(JsonValue bodyElem) {
    RigidBodyModel rbModel = new RigidBodyModel();
    rbModel.name = bodyElem.getString("name");
    rbModel.imagePath = bodyElem.getString("imagePath");

    JsonValue originElem = bodyElem.get("origin");
    rbModel.origin.x = originElem.getFloat("x");
    rbModel.origin.y = originElem.getFloat("y");

    // polygons/*from www  .  j  av  a 2 s  .  c o  m*/
    JsonValue polygonsElem = bodyElem.getChild("polygons");
    for (; polygonsElem != null; polygonsElem = polygonsElem.next()) {

        PolygonModel polygon = new PolygonModel();
        rbModel.polygons.add(polygon);

        JsonValue vertexElem = polygonsElem.child();
        for (; vertexElem != null; vertexElem = vertexElem.next()) {
            float x = vertexElem.getFloat("x");
            float y = vertexElem.getFloat("y");
            polygon.vertices.add(new Vector2(x, y));
        }

        polygon.buffer = new Vector2[polygon.vertices.size()];

    }

    // circles
    JsonValue circleElem = bodyElem.getChild("circles");

    for (; circleElem != null; circleElem = circleElem.next()) {
        CircleModel circle = new CircleModel();
        rbModel.circles.add(circle);

        circle.center.x = circleElem.getFloat("cx");
        circle.center.y = circleElem.getFloat("cy");
        circle.radius = circleElem.getFloat("r");
    }

    return rbModel;
}

From source file:br.com.questingsoftware.libgdx.g3db.G3DBConverter.java

License:Apache License

private void writeObject(JsonValue root, UBJsonWriter writer) throws IOException {
    if (root.type() == ValueType.array) {
        if (root.name() != null) {
            writer.array(root.name());/*www.ja va 2 s  . c om*/
        } else {
            writer.array();
        }
    } else {
        if (root.name() != null) {
            writer.object(root.name());
        } else {
            writer.object();
        }
    }

    JsonValue child = root.child();
    while (child != null) {
        switch (child.type()) {
        case booleanValue:
            if (child.name() != null) {
                writer.set(child.name(), child.asBoolean());
            } else {
                writer.value(child.asBoolean());
            }
            break;

        case doubleValue:
            if (child.name() != null) {
                writer.set(child.name(), child.asDouble());
            } else {
                writer.value(child.asDouble());
            }
            break;

        case longValue:
            if (child.name() != null) {
                writer.set(child.name(), child.asLong());
            } else {
                writer.value(child.asLong());
            }
            break;

        case stringValue:
            if (child.name() != null) {
                writer.set(child.name(), child.asString());
            } else {
                writer.value(child.asString());
            }
            break;

        case nullValue:
            if (child.name() != null) {
                writer.set(child.name());
            }
            break;

        case array:
        case object:
            writeObject(child, writer);
            break;
        }

        child = child.next();
    }

    writer.pop();
}

From source file:com.strategames.engine.storage.GameMetaData.java

License:Open Source License

@Override
public void read(Json json, JsonValue jsonData) {
    JsonValue child = jsonData.child();

    while (child != null) {
        if (child.name.contentEquals("uuid")) {
            uuid = child.asString();//from  w ww.j a v  a 2  s .  co  m
        } else if (child.name.contentEquals("name")) {
            name = child.asString();
        } else if (child.name.contentEquals("designer")) {
            designer = child.asString();
        } else if (child.name.contentEquals("info")) {
            parseAdditionalInfo(child.asString());
        }

        child = child.next();
    }
}

From source file:es.eucm.ead.buildtools.GenerateFieldClasses.java

License:Open Source License

private static String buildCode(Files files, Json json, String originJsonSchemaPath, String targetPackageName,
        String targetDirectory, boolean mainClass) {
    FileHandle fh = files.internal(originJsonSchemaPath);

    JsonValue next = json.fromJson(null, null, fh);
    next = next.child();

    String fieldsCode = "";
    String headerCode = "";
    String targetClassName = "";
    while ((next = next.next()) != null) {
        if (next.name().equals("properties")) {
            JsonValue nextProperty = next.child();
            fieldsCode += buildFields(nextProperty);
            break;
        } else if (next.name().equals("extends")) {
            String relativeParentJsonSchemaPath = next.child().asString();
            // Calculate directory to find parent class
            String parentJsonSchemaPath = originJsonSchemaPath.substring(0,
                    originJsonSchemaPath.lastIndexOf("/") + 1) + relativeParentJsonSchemaPath;
            fieldsCode += buildCode(files, json, parentJsonSchemaPath, null, null, false);
        } else if (next.name().equals("javaType") && mainClass) {
            String javaType = next.asString();
            String originalClassName = javaType.substring(javaType.lastIndexOf(".") + 1, javaType.length());
            targetClassName = originalClassName + "Fields";
            headerCode = getClassHeader(originalClassName, targetPackageName, targetClassName);
        }//from w ww .j a  v a  2 s.c om
    }

    if (mainClass) {
        if (fieldsCode.length() > 0) {
            System.out.println("Generating code for class " + targetClassName);
            String classCode = headerCode + fieldsCode + "}";
            writeClass(files, classCode, targetPackageName, targetClassName, targetDirectory);
            return classCode;
        } else {
            System.out.println("Skipping class " + targetClassName + " (no properties)");
            return "";
        }
    } else {
        return fieldsCode;
    }
}

From source file:es.eucm.ead.buildtools.GenerateFieldClasses.java

License:Open Source License

private static String buildFields(JsonValue nextProperty) {
    String classCode = "";
    while (nextProperty != null) {
        // Look for description
        JsonValue description = nextProperty.child();
        while (description != null && !description.name().equals("description")) {
            description = description.next();
        }//w w  w .  j a va  2s  .  co  m
        if (description != null) {
            classCode += "\t/**\n";
            classCode += "\t *" + description.asString() + "\n";
            classCode += "\t*/\n";
        }
        classCode += "\tpublic static final String " + nextProperty.name().toUpperCase() + " = \""
                + nextProperty.name() + "\";\n\n";
        nextProperty = nextProperty.next();
    }
    return classCode;
}

From source file:es.eucm.ead.engine.tracking.gleaner.GleanerGameTracker.java

License:Open Source License

/**
 * Configure the tracker//from ww w .  ja  v  a2s  .c  om
 *
 * @param config the json configuration
 */
private void configure(JsonValue config) {
    press = config.getBoolean(PRESS, false);
    phases = config.getBoolean(PHASES, false);
    tracker.setMaxTracesPerQueue(config.getInt(MAX_TRACES, -1));
    JsonValue variables = config.get(VARIABLES);
    if (variables != null) {
        if (variables.isArray()) {
            JsonValue current = variables.child();
            while (current != null) {
                this.watchField(current.asString());
                current = current.next();
            }
        } else {
            logger.warn("Invalid configuration value for variables. It should be an array of strings.");
        }
    }
}

From source file:mt.Json.java

License:Apache License

public void readFields(Object object, JsonValue jsonMap) {
    Class type = object.getClass();
    ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
    if (fields == null)
        fields = cacheFields(type);//from   ww  w  .  ja  v a  2 s. co m
    for (JsonValue child = jsonMap.child(); child != null; child = child.next()) {
        FieldMetadata metadata = fields.get(child.name());
        if (metadata == null) {
            if (ignoreUnknownFields) {
                if (debug)
                    System.out.println("Ignoring unknown field: " + child.name() + " (" + type.getName() + ")");
                continue;
            } else
                throw new SerializationException(
                        "Field not found: " + child.name() + " (" + type.getName() + ")");
        }
        Field field = metadata.field;
        // if (entry.value == null) continue; // I don't remember what this did. :(
        try {
            field.set(object, readValue(field.getType(), metadata.elementType, child));
        } catch (ReflectionException ex) {
            throw new SerializationException(
                    "Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex);
        } catch (SerializationException ex) {
            ex.addTrace(field.getName() + " (" + type.getName() + ")");
            throw ex;
        } catch (RuntimeException runtimeEx) {
            SerializationException ex = new SerializationException(runtimeEx);
            ex.addTrace(field.getName() + " (" + type.getName() + ")");
            throw ex;
        }
    }
}

From source file:mt.Json.java

License:Apache License

/** @param type May be null if the type is unknown.
 * @param elementType May be null if the type is unknown.
 * @return May be null. *//*  w  w  w  . j  a  v a  2 s  .  c  om*/
public <T> T readValue(Class<T> type, Class elementType, JsonValue jsonData) {
    if (jsonData == null)
        return null;

    if (jsonData.isObject()) {
        String className = typeName == null ? null : jsonData.getString(typeName, null);
        if (className != null) {
            jsonData.remove(typeName);
            try {
                type = (Class<T>) ClassReflection.forName(className);
            } catch (ReflectionException ex) {
                type = tagToClass.get(className);
                if (type == null)
                    throw new SerializationException(ex);
            }
        }

        Object object;
        if (type != null) {
            if (type == String.class || type == Integer.class || type == Boolean.class || type == Float.class
                    || type == Long.class || type == Double.class || type == Short.class || type == Byte.class
                    || type == Character.class || type.isEnum()) {
                return readValue("value", type, jsonData);
            }

            Serializer serializer = classToSerializer.get(type);
            if (serializer != null)
                return (T) serializer.read(this, jsonData, type);

            object = newInstance(type);

            if (object instanceof Serializable) {
                ((Serializable) object).read(this, jsonData);
                return (T) object;
            }

            if (object instanceof HashMap) {
                HashMap result = (HashMap) object;
                for (JsonValue child = jsonData.child(); child != null; child = child.next())
                    result.put(child.name(), readValue(elementType, null, child));
                return (T) result;
            }
        } else if (defaultSerializer != null) {
            return (T) defaultSerializer.read(this, jsonData, type);
        } else
            return (T) jsonData;

        if (object instanceof ObjectMap) {
            ObjectMap result = (ObjectMap) object;
            for (JsonValue child = jsonData.child(); child != null; child = child.next())
                result.put(child.name(), readValue(elementType, null, child));
            return (T) result;
        }
        readFields(object, jsonData);
        return (T) object;
    }

    if (type != null) {
        Serializer serializer = classToSerializer.get(type);
        if (serializer != null)
            return (T) serializer.read(this, jsonData, type);
    }

    if (jsonData.isArray()) {
        if ((type == null || type == Object.class) || ClassReflection.isAssignableFrom(Array.class, type)) {
            Array newArray = (type == null || type == Object.class) ? new Array() : (Array) newInstance(type);
            for (JsonValue child = jsonData.child(); child != null; child = child.next())
                newArray.add(readValue(elementType, null, child));
            return (T) newArray;
        }
        if (ClassReflection.isAssignableFrom(List.class, type)) {
            List newArray = (type == null || type.isInterface()) ? new ArrayList() : (List) newInstance(type);
            for (JsonValue child = jsonData.child(); child != null; child = child.next())
                newArray.add(readValue(elementType, null, child));
            return (T) newArray;
        }
        if (type.isArray()) {
            Class componentType = type.getComponentType();
            if (elementType == null)
                elementType = componentType;
            Object newArray = ArrayReflection.newInstance(componentType, jsonData.size);
            int i = 0;
            for (JsonValue child = jsonData.child(); child != null; child = child.next())
                ArrayReflection.set(newArray, i++, readValue(elementType, null, child));
            return (T) newArray;
        }
        throw new SerializationException(
                "Unable to convert value to required type: " + jsonData + " (" + type.getName() + ")");
    }

    if (jsonData.isNumber()) {
        try {
            if (type == null || type == float.class || type == Float.class)
                return (T) (Float) jsonData.asFloat();
            if (type == int.class || type == Integer.class)
                return (T) (Integer) jsonData.asInt();
            if (type == long.class || type == Long.class)
                return (T) (Long) jsonData.asLong();
            if (type == double.class || type == Double.class)
                return (T) (Double) (double) jsonData.asFloat();
            if (type == String.class)
                return (T) Float.toString(jsonData.asFloat());
            if (type == short.class || type == Short.class)
                return (T) (Short) (short) jsonData.asInt();
            if (type == byte.class || type == Byte.class)
                return (T) (Byte) (byte) jsonData.asInt();
        } catch (NumberFormatException ignored) {
        }
        jsonData = new JsonValue(jsonData.asString());
    }

    if (jsonData.isBoolean()) {
        try {
            if (type == null || type == boolean.class || type == Boolean.class)
                return (T) (Boolean) jsonData.asBoolean();
        } catch (NumberFormatException ignored) {
        }
        jsonData = new JsonValue(jsonData.asString());
    }

    if (jsonData.isString()) {
        String string = jsonData.asString();
        if (type == null || type == String.class)
            return (T) string;
        try {
            if (type == int.class || type == Integer.class)
                return (T) Integer.valueOf(string);
            if (type == float.class || type == Float.class)
                return (T) Float.valueOf(string);
            if (type == long.class || type == Long.class)
                return (T) Long.valueOf(string);
            if (type == double.class || type == Double.class)
                return (T) Double.valueOf(string);
            if (type == short.class || type == Short.class)
                return (T) Short.valueOf(string);
            if (type == byte.class || type == Byte.class)
                return (T) Byte.valueOf(string);
        } catch (NumberFormatException ignored) {
        }
        if (type == boolean.class || type == Boolean.class)
            return (T) Boolean.valueOf(string);
        if (type == char.class || type == Character.class)
            return (T) (Character) string.charAt(0);
        if (ClassReflection.isAssignableFrom(Enum.class, type)) {
            Object[] constants = type.getEnumConstants();
            for (int i = 0, n = constants.length; i < n; i++)
                if (string.equals(constants[i].toString()))
                    return (T) constants[i];
        }
        if (type == CharSequence.class)
            return (T) string;
        throw new SerializationException(
                "Unable to convert value to required type: " + jsonData + " (" + type.getName() + ")");
    }

    return null;
}

From source file:stu.tnt.gdx.widget.StyleAtlas.java

License:Apache License

protected Json getJsonLoader(final FileHandle skinFile) {
    final Skin skin = this;

    final Json json = new Json() {
        public <T> T readValue(Class<T> type, Class elementType, JsonValue jsonData) {
            // If the JSON is a string but the type is not, look up the
            // actual value by name.
            if (jsonData.isString() && !ClassReflection.isAssignableFrom(CharSequence.class, type))
                return get(jsonData.asString(), type);
            return super.readValue(type, elementType, jsonData);
        }/*from   w  w w .jav a  2 s. co m*/
    };
    json.setTypeName(null);
    json.setUsePrototypes(false);

    /* ------------------------------------------------ */

    json.setSerializer(Skin.class, new ReadOnlySerializer<Skin>() {
        public Skin read(Json json, JsonValue typeToValueMap, Class ignored) {
            for (JsonValue valueMap = typeToValueMap.child(); valueMap != null; valueMap = valueMap.next()) {
                try {
                    readNamedObjects(json, ClassReflection.forName(valueMap.name()), valueMap);
                } catch (ReflectionException ex) {
                    throw new SerializationException(ex);
                }
            }
            return skin;
        }

        private void readNamedObjects(Json json, Class type, JsonValue valueMap) {
            Class addType = type == TintedDrawable.class ? Drawable.class : type;
            for (JsonValue valueEntry = valueMap.child(); valueEntry != null; valueEntry = valueEntry.next()) {
                Object object = json.readValue(type, valueEntry);
                if (object == null)
                    continue;
                try {
                    add(valueEntry.name(), object, addType);
                } catch (Exception ex) {
                    throw new SerializationException(
                            "Error reading " + ClassReflection.getSimpleName(type) + ": " + valueEntry.name(),
                            ex);
                }
            }
        }
    });

    json.setSerializer(BitmapFont.class, new ReadOnlySerializer<BitmapFont>() {
        public BitmapFont read(Json json, JsonValue jsonData, Class type) {
            String path = json.readValue("file", String.class, jsonData);

            FileHandle fontFile = skinFile.parent().child(path);
            if (!fontFile.exists())
                fontFile = Gdx.files.internal(path);
            if (!fontFile.exists())
                throw new SerializationException("Font file not found: " + fontFile);

            // Use a region with the same name as the font, else use
            // a PNG file in the same directory as the FNT file.
            String regionName = fontFile.nameWithoutExtension();
            try {
                TextureRegion region = skin.optional(regionName, TextureRegion.class);
                if (region != null)
                    return new BitmapFont(fontFile, region, false);
                else {
                    FileHandle imageFile = fontFile.parent().child(regionName + ".png");
                    if (imageFile.exists())
                        return new BitmapFont(fontFile, imageFile, false);
                    else
                        return new BitmapFont(fontFile, false);
                }
            } catch (RuntimeException ex) {
                throw new SerializationException("Error loading bitmap font: " + fontFile, ex);
            }
        }
    });

    json.setSerializer(Color.class, new ReadOnlySerializer<Color>() {
        public Color read(Json json, JsonValue jsonData, Class type) {
            if (jsonData.isString())
                return get(jsonData.asString(), Color.class);
            String hex = json.readValue("hex", String.class, (String) null, jsonData);
            if (hex != null)
                return Color.valueOf(hex);
            float r = json.readValue("r", float.class, 0f, jsonData);
            float g = json.readValue("g", float.class, 0f, jsonData);
            float b = json.readValue("b", float.class, 0f, jsonData);
            float a = json.readValue("a", float.class, 1f, jsonData);
            return new Color(r, g, b, a);
        }
    });

    json.setSerializer(TintedDrawable.class, new ReadOnlySerializer() {
        public Object read(Json json, JsonValue jsonData, Class type) {
            String name = json.readValue("name", String.class, jsonData);
            Color color = json.readValue("color", Color.class, jsonData);
            return newDrawable(name, color);
        }
    });

    /* ------------------------------------------------ */

    json.setSerializer(Attributes.class, new ReadOnlySerializer<Attributes>() {
        @Override
        public Attributes read(Json json, JsonValue jsonData, Class type) {
            float startX = json.readValue("startX", float.class, (float) 0, jsonData);
            float startY = json.readValue("startY", float.class, (float) 0, jsonData);
            float dstX = json.readValue("x", float.class, jsonData);
            float dstY = json.readValue("y", float.class, jsonData);
            float width = json.readValue("width", float.class, jsonData);
            float height = json.readValue("height", float.class, jsonData);
            Attributes attr = new Attributes();
            attr.startX = startX;
            attr.startY = startY;
            attr.x = dstX;
            attr.y = dstY;
            attr.width = width;
            attr.height = height;
            return attr;
        }
    });

    /* ------------------------------------------------ */

    json.setSerializer(ScalingSet.class, new ReadOnlySerializer<ScalingSet>() {
        @Override
        public ScalingSet read(Json json, JsonValue jsonData, Class type) {
            float layoutx = json.readValue("layoutx", float.class, jsonData);
            float layouty = json.readValue("layouty", float.class, jsonData);
            float layoutwidth = json.readValue("layoutwidth", float.class, jsonData);
            float layoutheight = json.readValue("layoutheight", float.class, jsonData);
            float whratio = json.readValue("whratio", float.class, jsonData);
            float hwratio = json.readValue("hwratio", float.class, jsonData);
            return new ScalingSet().set(layoutx, layouty, layoutwidth, layoutheight, whratio, hwratio);
        }
    });

    /* ------------------------------------------------ */

    json.setSerializer(Vector2.class, new ReadOnlySerializer<Vector2>() {
        @Override
        public Vector2 read(Json json, JsonValue jsonData, Class type) {
            return new Vector2(json.readValue("x", float.class, jsonData),
                    json.readValue("y", float.class, jsonData));
        }
    });
    return json;
}