Example usage for com.google.gson JsonObject getAsJsonArray

List of usage examples for com.google.gson JsonObject getAsJsonArray

Introduction

In this page you can find the example usage for com.google.gson JsonObject getAsJsonArray.

Prototype

public JsonArray getAsJsonArray(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonArray.

Usage

From source file:at.tugraz.kmi.medokyservice.fca.util.ImportExport.java

License:Open Source License

private Map<Long, Domain> json2Domains(JsonObject json, Map<Long, FCAObject> objects,
        Map<Long, FCAAttribute> attributes, Map<Long, User> users, Map<Long, FCAItemMetadata> metadata) {

    Iterator<JsonElement> jsD = json.getAsJsonArray(SECTION_D).iterator();
    HashMap<Long, Domain> domains = new HashMap<Long, Domain>();
    while (jsD.hasNext()) {
        JsonObject d = jsD.next().getAsJsonObject();
        IncidenceMatrix mat = new IncidenceMatrix(d.get(NAME).getAsString(), d.get(DESCRIPTION).getAsString());
        Set<Entry<String, JsonElement>> mapping = d.get(MAPPING).getAsJsonObject().entrySet();
        JsonObject objMeta = d.get(SECTION_M).getAsJsonObject();
        for (Entry<String, JsonElement> map : mapping) {
            FCAObject object = objects.get(Long.parseLong(map.getKey()));
            FCAItemMetadata meta = metadata.get(objMeta.get(map.getKey()).getAsLong());
            System.out.println(object.getName());
            object.setLearningObjects(meta.getLearningObjects());
            object.setLearningObjectsByLearners(meta.getLearningObjectByLearner());
            String descr = object.getDescription();
            object.setDescription(meta.getDescription());
            mat.storeMetadata(object);//  w ww  .  j a v  a 2s.  co  m
            object.setDescription(descr);
            Iterator<JsonElement> atts = map.getValue().getAsJsonArray().iterator();
            HashSet<FCAAttribute> attribs = new HashSet<FCAAttribute>();
            while (atts.hasNext()) {
                long id = atts.next().getAsLong();
                FCAAttribute attr = attributes.get(id);
                attribs.add(attr);
                meta = metadata.get(objMeta.get(Long.toString(id)).getAsLong());
                attr.setLearningObjects(meta.getLearningObjects());
                descr = attr.getDescription();
                attr.setDescription(meta.getDescription());
                mat.storeMetadata(attr);
                attr.setDescription(descr);
            }
            mat.add(object, attribs);
        }
        boolean global = (d.get(GLOBAL) == null) ? false : d.get(GLOBAL).getAsBoolean();
        Domain domain;
        // compat
        try {
            domain = new Domain(mat.getName(), mat.getDescription(), mat, users.get(d.get(OWNER).getAsLong()),
                    global);
        } catch (Exception e) {
            // new format
            Set<User> owners = new HashSet<User>();

            Iterator<JsonElement> uIds = d.getAsJsonArray(OWNER).iterator();
            while (uIds.hasNext())
                owners.add(users.get(uIds.next().getAsLong()));
            domain = new Domain(mat.getName(), mat.getDescription(), mat, owners, global);
        }

        if (d.get(APPROVED) == null) {
            domain.setApproved(true);
        } else {
            domain.setApproved(d.get(APPROVED).getAsBoolean());
        }
        domains.put(d.get(ID).getAsLong(), domain);
    }
    return domains;
}

From source file:at.tugraz.kmi.medokyservice.fca.util.ImportExport.java

License:Open Source License

private Set<Course> json2Courses(JsonObject json, Map<Long, Domain> domains, Map<Long, User> users) {
    Set<Course> courses = new HashSet<Course>();
    Iterator<JsonElement> jsC = json.getAsJsonArray(SECTION_C).iterator();
    while (jsC.hasNext()) {
        JsonObject c = jsC.next().getAsJsonObject();
        Iterator<JsonElement> domainIds = c.getAsJsonArray(SECTION_D).iterator();
        Set<Domain> ddomains = new HashSet<Domain>();
        while (domainIds.hasNext()) {
            Domain domain = domains.get(domainIds.next().getAsLong());
            ddomains.add(domain);/* ww  w  .jav a 2s.  c  o m*/
        }

        Iterator<JsonElement> userIds = c.getAsJsonArray(PARTICIPANTS).iterator();
        Set<User> uusers = new HashSet<User>();
        while (userIds.hasNext()) {
            User u = users.get(userIds.next().getAsLong());
            uusers.add(u);
        }
        Course course = new Course(c.get(NAME).getAsString(), c.get(DESCRIPTION).getAsString(),
                c.get(E_CID).getAsString());

        for (Domain d : ddomains) {
            course.addDomain(d);
        }
        for (User u : uusers)
            course.addParticipant(u);
        courses.add(course);
    }
    return courses;
}

From source file:at.yawk.buycraft.BuycraftApiImpl.java

License:Mozilla Public License

@Override
public Set<Category> categories() throws IOException {
    JsonObject object = get("categories");
    Set<Category> categories = new HashSet<>();
    object.getAsJsonArray("payload").forEach(ele -> {
        JsonObject entry = ele.getAsJsonObject();
        Category category = new Category(entry.get("id").getAsInt(), entry.get("name").getAsString(),
                entry.get("shortDescription").getAsString(), entry.get("guiItemId").getAsInt(),
                entry.get("itemId").getAsString());
        categories.add(category);/*  w ww .  j av  a  2 s .  c o  m*/
    });
    return categories;
}

From source file:at.yawk.buycraft.BuycraftApiImpl.java

License:Mozilla Public License

@Override
public Set<Package> packages() throws IOException {
    JsonObject object = get("packages");
    Set<Package> packages = new HashSet<>();
    object.getAsJsonArray("payload").forEach(ele -> {
        JsonObject entry = ele.getAsJsonObject();
        Package pack = new Package(entry.get("id").getAsInt(), entry.get("order").getAsInt(),
                entry.get("name").getAsString(), entry.get("description").getAsString(),
                entry.get("shortDescription").getAsString(), entry.get("price").getAsString(),
                entry.get("category").getAsInt(), entry.get("guiItemId").getAsInt(),
                entry.get("itemId").getAsString());
        packages.add(pack);//from  w  w w .j  av a2 s  .  c om
    });
    return packages;
}

From source file:at.yawk.buycraft.BuycraftApiImpl.java

License:Mozilla Public License

@Override
public Set<Purchase> payments(String limit, Optional<String> user) throws IOException {
    URIBuilder builder = new URIBuilder();
    builder.setParameter("limit", limit);
    user.ifPresent(u -> builder.setParameter("ign", u));
    JsonObject object = get("payments", builder);
    Set<Purchase> purchases = new HashSet<>();
    object.getAsJsonArray("payload").forEach(ele -> {
        JsonObject entry = ele.getAsJsonObject();
        List<Integer> packages = new ArrayList<>();
        entry.getAsJsonArray("packages").forEach(pack -> packages.add(pack.getAsInt()));
        Purchase purchase = new Purchase(entry.get("time").getAsLong(), entry.get("humanTime").getAsString(),
                entry.get("ign").getAsString(), entry.get("uuid").getAsString(),
                entry.get("price").getAsString(), entry.get("currency").getAsString(),
                Collections.unmodifiableCollection(packages));
        purchases.add(purchase);/*from w ww.  j av  a 2 s . co  m*/
    });
    return purchases;
}

From source file:at.yawk.buycraft.BuycraftApiImpl.java

License:Mozilla Public License

@Override
public PendingResponse pending() throws IOException {
    JsonObject object = get("pendingUsers");
    List<String> pending = new ArrayList<>();
    JsonObject payload = object.getAsJsonObject("payload");
    payload.getAsJsonArray("pendingPlayers").forEach(ele -> pending.add(ele.getAsString()));
    return new PendingResponse(Collections.unmodifiableCollection(pending),
            payload.get("offlineCommands").getAsBoolean());
}

From source file:bammerbom.ultimatecore.bukkit.resources.utils.JsonRepresentedObject.java

License:MIT License

/**
 * Deserializes a fancy message from its JSON representation. This JSON
 * representation is of the format of that returned by
 * {@link #toJSONString()}, and is compatible with vanilla inputs.
 *
 * @param json The JSON string which represents a fancy message.
 * @return A {@code MessageUtil} representing the parameterized JSON
 * message.//www  .j  ava 2 s  .  co m
 */
public static MessageUtil deserialize(String json) {
    JsonObject serialized = _stringParser.parse(json).getAsJsonObject();
    JsonArray extra = serialized.getAsJsonArray("extra"); // Get the extra component
    MessageUtil returnVal = new MessageUtil();
    returnVal.messageParts.clear();
    for (JsonElement mPrt : extra) {
        MessagePart component = new MessagePart();
        JsonObject messagePart = mPrt.getAsJsonObject();
        for (Map.Entry<String, JsonElement> entry : messagePart.entrySet()) {
            // Deserialize text
            if (TextualComponent.isTextKey(entry.getKey())) {
                // The map mimics the YAML serialization, which has a "key" field and one or more "value" fields
                Map<String, Object> serializedMapForm = new HashMap<>(); // Must be object due to Bukkit serializer API compliance
                serializedMapForm.put("key", entry.getKey());
                if (entry.getValue().isJsonPrimitive()) {
                    // Assume string
                    serializedMapForm.put("value", entry.getValue().getAsString());
                } else {
                    // Composite object, but we assume each element is a string
                    for (Map.Entry<String, JsonElement> compositeNestedElement : entry.getValue()
                            .getAsJsonObject().entrySet()) {
                        serializedMapForm.put("value." + compositeNestedElement.getKey(),
                                compositeNestedElement.getValue().getAsString());
                    }
                }
                component.text = TextualComponent.deserialize(serializedMapForm);
            } else if (MessagePart.stylesToNames.inverse().containsKey(entry.getKey())) {
                if (entry.getValue().getAsBoolean()) {
                    component.styles.add(MessagePart.stylesToNames.inverse().get(entry.getKey()));
                }
            } else if (entry.getKey().equals("color")) {
                component.color = ChatColor.valueOf(entry.getValue().getAsString().toUpperCase());
            } else if (entry.getKey().equals("clickEvent")) {
                JsonObject object = entry.getValue().getAsJsonObject();
                component.clickActionName = object.get("action").getAsString();
                component.clickActionData = object.get("value").getAsString();
            } else if (entry.getKey().equals("hoverEvent")) {
                JsonObject object = entry.getValue().getAsJsonObject();
                component.hoverActionName = object.get("action").getAsString();
                if (object.get("value").isJsonPrimitive()) {
                    // Assume string
                    component.hoverActionData = new JsonString(object.get("value").getAsString());
                } else {
                    // Assume composite type
                    // The only composite type we currently store is another MessageUtil
                    // Therefore, recursion time!
                    component.hoverActionData = deserialize(object.get("value")
                            .toString() /* This should properly serialize the JSON object as a JSON string */);
                }
            } else if (entry.getKey().equals("insertion")) {
                component.insertionData = entry.getValue().getAsString();
            } else if (entry.getKey().equals("with")) {
                for (JsonElement object : entry.getValue().getAsJsonArray()) {
                    if (object.isJsonPrimitive()) {
                        component.translationReplacements.add(new JsonString(object.getAsString()));
                    } else {
                        // Only composite type stored in this array is - again - MessageUtils
                        // Recurse within this function to parse this as a translation replacement
                        component.translationReplacements.add(deserialize(object.toString()));
                    }
                }
            }
        }
        returnVal.messageParts.add(component);
    }
    return returnVal;
}

From source file:bean.EJBean.java

License:Open Source License

public Edificio getEdificio(String id) {

    client = ClientBuilder.newClient();//w  ww.ja v  a2s.com
    String edificio = client.target(baseURI).path("edificios").path(id).request(MediaType.APPLICATION_JSON)
            .get(String.class);
    client.close();

    /// Deserializar///

    GsonBuilder gsonBuilder = new GsonBuilder();

    JsonDeserializer<Edificio> deserializer = new JsonDeserializer<Edificio>() {

        @Override
        public Edificio deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            JsonObject jsonObject = json.getAsJsonObject();

            Edificio e = new Edificio();

            e.setIdedificio(jsonObject.get("idedificio").getAsString());

            if (jsonObject.has("nombreen")) {
                e.setNombreen(jsonObject.get("nombreen").getAsString());
            }
            if (jsonObject.has("nombrevl")) {
                e.setNombrevl(jsonObject.get("nombrevl").getAsString());
            }
            if (jsonObject.has("nombrees")) {
                e.setNombrees(jsonObject.get("nombrees").getAsString());
            }
            if (jsonObject.has("direccion")) {
                e.setDireccion(jsonObject.get("direccion").getAsString());
            }
            if (jsonObject.has("telefono")) {
                e.setTelefono(jsonObject.get("telefono").getAsString());
            }
            if (jsonObject.has("enlace")) {
                e.setEnlace(jsonObject.get("enlace").getAsString());
            }
            e.setXano(jsonObject.get("xano").getAsString());
            e.setTopleft(jsonObject.get("topleft").getAsString());
            e.setTopright(jsonObject.get("topright").getAsString());
            e.setBottomleft(jsonObject.get("bottomleft").getAsString());

            // System.out.println("Deserializer: Edi Obj: "+e.toString());

            List<Usuario> lu = new ArrayList<Usuario>();
            JsonArray usuariosArray = jsonObject.getAsJsonArray("usuarios");
            for (JsonElement usuario : usuariosArray) {
                Usuario u = new Usuario();
                JsonObject usuarioObj = usuario.getAsJsonObject();
                u.setUsuario(usuarioObj.get("usuario").getAsString());
                lu.add(u);
            }
            // System.out.println("Deserializer: usu Obj: "+e.toString());

            e.setUsuarios(lu);
            // System.out.println("Deserializer: usu Obj: " + e.getUsuarios().size());
            List<Plano> lp = new ArrayList<Plano>();
            JsonArray planoArray = jsonObject.getAsJsonArray("planos");
            for (JsonElement plano : planoArray) {
                Plano p = new Plano();
                PlanoPK pk = new PlanoPK();
                JsonObject planoObj = plano.getAsJsonObject();
                pk.setIdedificio(e.getIdedificio());
                pk.setIdplano(planoObj.get("idplano").getAsString());
                p.setId(pk);
                p.setEnlace(planoObj.get("enlace").getAsString());
                p.setNivel(planoObj.get("nivel").getAsInt());
                Edificio edAux = new Edificio();
                edAux.setIdedificio(edAux.getIdedificio());
                p.setEdificio(edAux);

                lp.add(p);
            }

            e.setPlanos(lp);

            JsonObject coordenadaObj = jsonObject.getAsJsonObject("coordenada");
            Coordenada coordenada = new Coordenada();
            coordenada.setIdcoordenada(coordenadaObj.get("idcoordenada").getAsString());
            coordenada.setDescripcion(coordenadaObj.get("idcoordenada").getAsString());
            coordenada.setLatitud(coordenadaObj.get("latitud").getAsDouble());
            coordenada.setLongitud(coordenadaObj.get("longitud").getAsDouble());

            e.setCoordenada(coordenada);

            return e;
        }

    };
    gsonBuilder.registerTypeAdapter(Edificio.class, deserializer);

    System.out.println("GSON" + edificio);

    Gson customGson = gsonBuilder.create();
    Edificio jsonToEdificio = customGson.fromJson(edificio, Edificio.class);
    System.out.print("Size users EJB: " + jsonToEdificio.getUsuarios().size());

    return jsonToEdificio;
}

From source file:bean.EJBean.java

License:Open Source License

public Espacio getEspacio(String id) {
    client = ClientBuilder.newClient();/* ww w  . j a v a  2s  .c  o m*/
    String espacio = client.target(baseURI).path("espacios").path(id).request(MediaType.APPLICATION_JSON)
            .get(String.class);
    client.close();

    /// Deserializar///

    //      System.out.println(espacio);

    GsonBuilder gsonBuilder = new GsonBuilder();

    JsonDeserializer<Espacio> deserializer = new JsonDeserializer<Espacio>() {

        @Override
        public Espacio deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            JsonObject jsonObject = json.getAsJsonObject();

            Espacio e = new Espacio();

            e.setIdespacio(jsonObject.get("idespacio").getAsString());

            if (jsonObject.has("nombreen")) {
                e.setNombreen(jsonObject.get("nombreen").getAsString());
            }
            if (jsonObject.has("nombrevl")) {
                e.setNombrevl(jsonObject.get("nombrevl").getAsString());
            }
            if (jsonObject.has("nombrees")) {
                e.setNombrees(jsonObject.get("nombrees").getAsString());
            }
            if (jsonObject.has("bloque")) {
                e.setBloque(jsonObject.get("bloque").getAsString());
            }
            if (jsonObject.has("piso")) {
                e.setPiso(jsonObject.get("piso").getAsInt());
            }
            if (jsonObject.has("tipo")) {
                e.setTipo(jsonObject.get("tipo").getAsString());
            }
            e.setVisibilidad(jsonObject.get("visibilidad").getAsBoolean());
            if (jsonObject.has("boundingbox")) {
                e.setBoundingbox(jsonObject.get("boundingbox").getAsString());
            }

            // System.out.println("Deserializer: Edi Obj: "+e.toString());
            JsonObject edificioObj = jsonObject.getAsJsonObject("edificio");
            Edificio edificio = new Edificio();
            edificio.setIdedificio(edificioObj.get("idedificio").getAsString());

            e.setEdificio(edificio);

            List<Panorama> lp = new ArrayList<Panorama>();
            JsonArray panoArray = jsonObject.getAsJsonArray("panoramas");
            for (JsonElement pano : panoArray) {
                Panorama p = new Panorama();
                JsonObject panoObj = pano.getAsJsonObject();
                p.setIdpanorama(panoObj.get("idpanorama").getAsString());
                p.setEnlace(panoObj.get("enlace").getAsString());
                lp.add(p);
            }

            e.setPanoramas(lp);

            JsonObject coordenadaObj = jsonObject.getAsJsonObject("coordenada");
            Coordenada coordenada = new Coordenada();
            coordenada.setIdcoordenada(coordenadaObj.get("idcoordenada").getAsString());
            coordenada.setDescripcion(coordenadaObj.get("idcoordenada").getAsString());
            coordenada.setLatitud(coordenadaObj.get("latitud").getAsDouble());
            coordenada.setLongitud(coordenadaObj.get("longitud").getAsDouble());

            e.setCoordenada(coordenada);

            if (jsonObject.has("profesores")) {
                List<Profesor> lprof = new ArrayList<Profesor>();
                JsonArray profArray = jsonObject.getAsJsonArray("profesores");
                for (JsonElement prof : profArray) {
                    Profesor p = new Profesor();
                    JsonObject profObj = prof.getAsJsonObject();
                    p.setIdprofesor(profObj.get("idprofesor").getAsString());
                    p.setUsuario(profObj.get("usuario").getAsString());
                    p.setVisibilidad(profObj.get("visibilidad").getAsBoolean());

                    lprof.add(p);
                }

                e.setProfesores(lprof);
            }

            return e;
        }

    };
    gsonBuilder.registerTypeAdapter(Espacio.class, deserializer);

    // System.out.println("GSON"+espacio);

    Gson customGson = gsonBuilder.create();
    Espacio jsonToEspacio = customGson.fromJson(espacio, Espacio.class);

    return jsonToEspacio;
}

From source file:bean.EJBean.java

License:Open Source License

public List<Espacio> getEspaciosFromEdificio(String id) {

    client = ClientBuilder.newClient();/*w w w  .j a  v  a2  s  .  c o m*/
    String espaciosJSON = client.target(baseURI).path("edificios").path(id).path("espacios")
            .request(MediaType.APPLICATION_JSON).get(String.class);
    client.close();

    GsonBuilder gsonBuilder = new GsonBuilder();

    JsonDeserializer<Espacio> deserializer = new JsonDeserializer<Espacio>() {

        @Override
        public Espacio deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
            JsonObject jsonObject = json.getAsJsonObject();

            Espacio e = new Espacio();

            // System.out.println("HOLA "+jsonObject.get("bloque").getAsString());

            e.setIdespacio(jsonObject.get("idespacio").getAsString());
            e.setNombrees(jsonObject.get("nombrees").getAsString());
            // e.setNombreen(jsonObject.get("nombreen").getAsString());
            // e.setNombrevl(jsonObject.get("nombrevl").getAsString());
            e.setBloque(jsonObject.get("bloque").getAsString());
            e.setBoundingbox(jsonObject.get("boundingbox").getAsString());
            e.setPiso(jsonObject.get("piso").getAsInt());
            e.setTipo(jsonObject.get("tipo").getAsString());
            e.setVisibilidad(jsonObject.get("visibilidad").getAsBoolean());

            JsonObject coordenadaObj = jsonObject.getAsJsonObject("coordenada");
            Coordenada coordenada = new Coordenada();
            coordenada.setIdcoordenada(coordenadaObj.get("idcoordenada").getAsString());
            coordenada.setDescripcion(coordenadaObj.get("idcoordenada").getAsString());
            coordenada.setLatitud(coordenadaObj.get("latitud").getAsDouble());
            coordenada.setLongitud(coordenadaObj.get("longitud").getAsDouble());
            e.setCoordenada(coordenada);

            JsonObject edificioObj = jsonObject.getAsJsonObject("edificio");
            Edificio edificio = new Edificio();
            edificio.setIdedificio(edificioObj.get("idedificio").getAsString());
            /*
             * edificio.setNombrees(edificioObj.get("nombrees").getAsString());
             * edificio.setNombreen(edificioObj.get("nombreen").getAsString());
             * edificio.setNombrevl(edificioObj.get("nombrevl").getAsString());
             * edificio.setEnlace(edificioObj.get("enlace").getAsString());
             * edificio.setXano(edificioObj.get("xano").getAsString());
             * edificio.setTopleft(edificioObj.get("topleft").getAsString());
             * edificio.setTopright(edificioObj.get("topright").getAsString());
             * edificio.setBottomleft(edificioObj.get("bottomleft").getAsString());
             */
            e.setEdificio(edificio);

            List<Panorama> lu = new ArrayList<Panorama>();
            JsonArray panoramaArray = jsonObject.getAsJsonArray("panoramas");
            for (JsonElement panorama : panoramaArray) {
                Panorama p = new Panorama();

                JsonObject panoramaObj = panorama.getAsJsonObject();

                p.setIdpanorama(panoramaObj.get("idpanorama").getAsString());
                p.setEnlace(panoramaObj.get("enlace").getAsString());
                if (panoramaObj.has("panorama")) {
                    p.setPanorama(panoramaObj.get("panorama").getAsInt());
                }

                lu.add(p);
            }

            e.setPanoramas(lu);

            List<Profesor> lp = new ArrayList<Profesor>();
            if (jsonObject.has("profesores")) {
                JsonArray profesorArray = jsonObject.getAsJsonArray("profesores");
                for (JsonElement profesor : profesorArray) {
                    Profesor p = new Profesor();

                    JsonObject profesorObj = profesor.getAsJsonObject();
                    p.setIdprofesor(profesorObj.get("idprofesor").getAsString());
                    p.setUsuario(profesorObj.get("usuario").getAsString());
                    p.setVisibilidad(profesorObj.get("visibilidad").getAsBoolean());
                    lp.add(p);
                }
            }
            e.setProfesores(lp);

            return e;
        }

    };
    gsonBuilder.registerTypeAdapter(Espacio.class, deserializer);

    Type listType = new TypeToken<List<Espacio>>() {
    }.getType();

    Gson customGson = gsonBuilder.create();
    List<Espacio> jsonToEspacios = customGson.fromJson(espaciosJSON, listType);

    // System.out.println("Success Espacio: "+ jsonToEspacios.size());

    return jsonToEspacios;

}