Example usage for com.google.gson JsonElement getAsJsonArray

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

Introduction

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

Prototype

public JsonArray getAsJsonArray() 

Source Link

Document

convenience method to get this element as a JsonArray .

Usage

From source file:co.aurasphere.botmill.kik.util.json.IncomingMessagesDeserializer.java

License:Open Source License

@SuppressWarnings("incomplete-switch")
public MessageCallback deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    MessageCallback messageCallback = new MessageCallback();
    //   The message callback can have multiple message bodies.
    JsonElement jsonMessages = json.getAsJsonObject().get("messages");

    for (int i = 0; i < jsonMessages.getAsJsonArray().size(); i++) {
        //   get type.
        JsonObject jsonMessage = jsonMessages.getAsJsonArray().get(i).getAsJsonObject();
        String typeString = jsonMessage.get("type").getAsString();
        MessageType messageType = MessageType.valueOf(typeString.replace('-', '_').toUpperCase());
        Class<? extends Message> messageClass = null;
        switch (messageType) {
        case TEXT:
            messageClass = TextMessage.class;
            break;
        case PICTURE:
            messageClass = PictureMessage.class;
            break;
        case VIDEO:
            messageClass = VideoMessage.class;
            break;
        case LINK:
            messageClass = LinkMessage.class;
            break;
        case SCAN_DATA:
            messageClass = ScanDataMessage.class;
            break;
        case STICKER:
            messageClass = StickerMessage.class;
            break;
        case FRIEND_PICKER:
            messageClass = FriendPickerMessage.class;
            break;
        case IS_TYPING:
            messageClass = IsTypingMessage.class;
            break;
        case READ_RECEIPT:
            messageClass = ReadReceiptMessage.class;
            break;
        case START_CHATTING:
            messageClass = StartChattingMessage.class;
            break;
        }// w  w  w . jav a  2  s  .c o m

        Message message = context.deserialize(jsonMessage, messageClass);
        messageCallback.addMessage(message);
    }

    return messageCallback;
}

From source file:co.cask.cdap.api.dataset.lib.partitioned.ComparableCodec.java

License:Apache License

@Nullable
protected Comparable deserializeComparable(@Nullable JsonElement comparableJson,
        JsonDeserializationContext jsonDeserializationContext) {
    if (comparableJson == null) {
        return null;
    }/*from   w  ww  .  j  av  a2s . c  om*/
    JsonArray jsonArray = comparableJson.getAsJsonArray();
    // the classname is serialized as the first element, the value is serialized as the second
    Class<? extends Comparable> comparableClass = forName(jsonArray.get(0).getAsString());
    return jsonDeserializationContext.deserialize(jsonArray.get(1), comparableClass);
}

From source file:co.cask.cdap.common.zookeeper.coordination.ResourceAssignmentTypeAdapter.java

License:Apache License

@Override
public ResourceAssignment deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    if (!json.isJsonObject()) {
        throw new JsonParseException("Expect a json object, got " + json);
    }/* w  ww .j a  v  a 2 s  . c  o m*/

    JsonObject jsonObj = json.getAsJsonObject();
    String name = jsonObj.get("name").getAsString();

    Multimap<Discoverable, PartitionReplica> assignments = TreeMultimap
            .create(DiscoverableComparator.COMPARATOR, PartitionReplica.COMPARATOR);
    JsonArray assignmentsJson = context.deserialize(jsonObj.get("assignments"), JsonArray.class);
    for (JsonElement element : assignmentsJson) {
        if (!element.isJsonArray()) {
            throw new JsonParseException("Expect a json array, got " + element);
        }

        JsonArray entryJson = element.getAsJsonArray();
        if (entryJson.size() != 2) {
            throw new JsonParseException("Expect json array of size = 2, got " + entryJson.size());
        }
        Discoverable key = context.deserialize(entryJson.get(0), Discoverable.class);
        PartitionReplica value = context.deserialize(entryJson.get(1), PartitionReplica.class);
        assignments.put(key, value);
    }

    return new ResourceAssignment(name, assignments);
}

From source file:co.cask.cdap.passport.http.client.PassportClient.java

License:Apache License

/**
 * Get List of VPC for the apiKey.// ww w .  j av  a  2 s  .  co  m
 * @return List of VPC Names
 */
public List<String> getVPCList(String apiKey) {
    Preconditions.checkNotNull(apiKey, "ApiKey cannot be null");
    List<String> vpcList = Lists.newArrayList();

    try {
        String data = responseCache.getIfPresent(apiKey);

        if (data == null) {
            data = httpGet(API_BASE + "vpc/list", apiKey);
            if (data != null) {
                responseCache.put(apiKey, data);
            }
        }

        if (data != null) {
            JsonParser parser = new JsonParser();
            JsonElement element = parser.parse(data);
            JsonArray jsonArray = element.getAsJsonArray();

            for (JsonElement elements : jsonArray) {
                JsonObject vpc = elements.getAsJsonObject();
                if (vpc.get("vpc_name") != null) {
                    vpcList.add(vpc.get("vpc_name").getAsString());
                }
            }
        }
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
    return vpcList;
}

From source file:co.com.codesoftware.facturacion.ajax.controlador.AjaxControllerFacturacion.java

public ArrayList<ProductosFactEntitiy> generaListaProductos() {
    JsonElement json = new JsonParser().parse(this.productosArray);
    JsonArray array = json.getAsJsonArray();
    Iterator iterator = array.iterator();
    ArrayList<ProductosFactEntitiy> productosList = null;
    while (iterator.hasNext()) {
        if (productosList == null) {
            productosList = new ArrayList<>();
        }/* ww  w  . ja  v  a  2 s. c o  m*/
        JsonElement json2 = (JsonElement) iterator.next();
        Gson gson = new Gson();
        ProductosFactEntitiy prod = gson.fromJson(json2, ProductosFactEntitiy.class);
        productosList.add(prod);
    }
    return productosList;
}

From source file:co.vaughnvernon.tradercommon.media.AbstractJSONMediaReader.java

License:Apache License

public JsonArray array(String... aKeys) {
    JsonArray array = null;//from   w ww . j av  a2s .c o  m

    JsonElement element = this.navigateTo(this.representation(), aKeys);

    if (element != null) {
        array = element.getAsJsonArray();
    }

    return array;
}

From source file:com.addthis.hydra.task.source.bundleizer.GsonBundleizer.java

License:Apache License

public ValueObject fromGson(JsonElement gson) {
    if (gson.isJsonNull()) {
        return null;
    } else if (gson.isJsonObject()) {
        JsonObject object = gson.getAsJsonObject();
        ValueMap map = ValueFactory.createMap();
        for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
            map.put(entry.getKey(), fromGson(entry.getValue()));
        }//from w w w. j a  v a  2  s .  co m
        return map;
    } else if (gson.isJsonArray()) {
        JsonArray gsonArray = gson.getAsJsonArray();
        ValueArray valueArray = ValueFactory.createArray(gsonArray.size());
        for (JsonElement arrayElement : gsonArray) {
            valueArray.add(fromGson(arrayElement));
        }
        return valueArray;
    } else {
        JsonPrimitive primitive = gson.getAsJsonPrimitive();
        if (primitive.isNumber()) {
            return ValueFactory.create(primitive.getAsDouble());
        } else {
            return ValueFactory.create(primitive.getAsString());
        }
    }
}

From source file:com.adobe.acs.commons.json.JsonObjectUtil.java

License:Apache License

public static boolean isSingularElement(JsonElement elem) {
    return elem.isJsonPrimitive() || (elem.isJsonArray() && elem.getAsJsonArray().size() <= 1);
}

From source file:com.adobe.acs.commons.remoteassets.impl.RemoteAssetsNodeSyncImpl.java

License:Apache License

/**
 * Create or update resources from remote JSON.
 *
 * @param json JsonObject//from  w w  w  .  j a v  a2s  .  com
 * @param resource Resource
 * @throws IOException exception
 * @throws RepositoryException exception
 */
private void createOrUpdateNodes(final ResourceResolver remoteAssetsResolver, final JsonObject json,
        final Resource resource) throws IOException, RepositoryException {
    for (Map.Entry<String, JsonElement> jsonEntry : json.entrySet()) {
        JsonElement jsonElement = jsonEntry.getValue();
        if (jsonElement.isJsonObject()) {
            createOrUpdateNodesForJsonObject(remoteAssetsResolver, jsonEntry.getKey(), resource);
        } else if (jsonElement.isJsonArray()) {
            setNodeArrayProperty(remoteAssetsResolver, jsonEntry.getKey(), jsonElement.getAsJsonArray(),
                    resource);
        } else {
            setNodeProperty(remoteAssetsResolver, jsonEntry.getKey(), json, resource);
        }
    }
}

From source file:com.ajax.admin.AdminHomeAjax.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from  ww w . jav a2  s .  co m
        if (conn == null || conn.isClosed()) {
            conn = (Connection) DBUtil.getConnection();
        }
        type = request.getParameter("type");
        System.out.println("Type : " + type);
        part_name = request.getParameter("part_name");
        String venu_manager = request.getParameter("venu_manager");
        String comp_name = request.getParameter("comp_name");
        City = request.getParameter("City");
        lead_status = request.getParameter("lead_status");
        branch_id = request.getParameter("branch_id");
        System.out.println("branch_id : " + branch_id);
        String mySiteId = request.getParameter("mySiteId");
        String userMail = request.getParameter("myUserId");
        if (type.equals("meter")) {
            meterD = meterDetails.getAllData(part_name, conn);// ajax
            gson = new Gson();
            JsonElement element = gson.toJsonTree(meterD, new TypeToken<List<MeterDetails>>() {
            }.getType());
            JsonArray jsonArray = element.getAsJsonArray();
            response.setContentType("application/json");
            response.getWriter().print(jsonArray);
        } else if (type.equals("assignedTo")) {
            lookup = lookupD.getype(conn);// ajax
            gson = new Gson();
            JsonElement element = gson.toJsonTree(lookup, new TypeToken<List<LookupMaster>>() {
            }.getType());
            JsonArray jsonArray = element.getAsJsonArray();
            response.setContentType("application/json");
            response.getWriter().print(jsonArray);
        } else if (type.equals("assignedTo1")) {
            List<String> lookupAssigned = serviceReqDao.getLookUpAssigned(branch_id, mySiteId, userMail, conn);
            gson = new Gson();
            JsonElement element = gson.toJsonTree(lookupAssigned, new TypeToken<List<String>>() {
            }.getType());
            JsonArray jsonArray = element.getAsJsonArray();
            response.setContentType("application/json");
            response.getWriter().print(jsonArray);
        } else if (type.equals("raisedBy")) {
            String first_name = serviceReqDao.getRaisedBy(userMail, conn);
            List<String> First_name = new ArrayList<String>();
            First_name.add(first_name);
            gson = new Gson();
            JsonElement element = gson.toJsonTree(First_name, new TypeToken<List<String>>() {
            }.getType());
            JsonArray jsonArray = element.getAsJsonArray();
            response.setContentType("application/json");
            response.getWriter().print(jsonArray);
        } else if (type.equals("property_report")) {
            System.out.println("Inside property report");
            list_Space = enqReport.getAllEnquery(venu_manager, conn);
            gson = new Gson();
            JsonElement element = gson.toJsonTree(list_Space, new TypeToken<List<List_your_space>>() {
            }.getType());
            JsonArray jsonArray = element.getAsJsonArray();
            response.setContentType("application/json");
            response.getWriter().print(jsonArray);
        } else if (type.equals("business_enquiry_details")) {
            System.out.println("Inside business enquiry ");
            list_Space = enqReport.getAllEnqReport(venu_manager, comp_name, conn);
            System.out.println(list_Space);
            for (List_your_space list_your_space : list_Space) {
                System.out.println(list_your_space.getProperty_Name());
                System.out.println(list_your_space.getStatus());
            }
            gson = new Gson();
            JsonElement element = gson.toJsonTree(list_Space, new TypeToken<List<List_your_space>>() {
            }.getType());
            JsonArray jsonArray = element.getAsJsonArray();
            response.setContentType("application/json");
            response.getWriter().print(jsonArray);
        } else if (type.equals("admin_partner_list")) {
            String cities = request.getParameter("city");
            partD = partnerRep.getAllPartners(cities, conn);
            gson = new Gson();
            JsonElement element = gson.toJsonTree(partD, new TypeToken<List<PartnerDetails>>() {
            }.getType());
            JsonArray jsonArray = element.getAsJsonArray();
            response.setContentType("application/json");
            response.getWriter().print(jsonArray);
        } else if (type.equals("admin_member_list")) {
            newmember = newMemberReg.getAllEnqReport(venu_manager, conn);// ajax
            gson = new Gson();
            JsonElement element = gson.toJsonTree(newmember, new TypeToken<List<NewMemberReg>>() {
            }.getType());
            JsonArray jsonArray = element.getAsJsonArray();
            response.setContentType("application/json");
            response.getWriter().print(jsonArray);
        }

        else if (type.equals("post_requirement")) {
            reqlist = postreq.getAllRequirement(City, lead_status, conn);// ajax
            Gson gson = new Gson();
            JsonElement element = gson.toJsonTree(reqlist, new TypeToken<List<Post_req_list>>() {
            }.getType());
            JsonArray jsonArray = element.getAsJsonArray();
            response.setContentType("application/json");
            response.getWriter().print(jsonArray);
        } else if (type.equals("business_enquiry_report")) {
            String enquiry_id = request.getParameter("enquiry_id");
            list_Space = enqReport.getAllUpdate(enquiry_id, conn);// ajax
            gson = new Gson();
            JsonElement element = gson.toJsonTree(list_Space, new TypeToken<List<List_your_space>>() {
            }.getType());
            jsonArray = element.getAsJsonArray();
            response.setContentType("application/json");
            response.getWriter().print(jsonArray);
        } else if (type.equals("admin_member_update")) {
            String profile_number = request.getParameter("profile_number");
            tree = newMemberReg.getAllUpdates(profile_number, conn);// ajax
            System.out.println("my name: " + newmember);
            gson = new Gson();
            JsonElement element = gson.toJsonTree(tree, new TypeToken<List<NewMemberReg>>() {
            }.getType());
            jsonArray = element.getAsJsonArray();
            response.setContentType("application/json");
            response.getWriter().print(jsonArray);
        }
        // Close connection
        if (conn != null || !conn.isClosed()) {
            DBUtil.closeConnection(conn);
            System.out.println(conn + " Connection closed");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}