Example usage for com.google.gson JsonObject toString

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

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Returns a String representation of this element.

Usage

From source file:com.eventual.websockets.ChatWS.java

private void notificarMensaje(int emisor, int destintario, String texto) {

    UsuarioConectado usuario = this.chat.getConectados().get(destintario);
    if (usuario != null) {
        try {//from ww  w.j  a  va2s  .co m
            // Conectado
            JsonObject mensaje = new JsonObject();
            mensaje.addProperty("tipo", "MENSAJE");
            mensaje.addProperty("emisor", emisor);
            mensaje.addProperty("destintario", destintario);
            mensaje.addProperty("texto", texto);
            usuario.getSesion().getBasicRemote().sendText(mensaje.toString());
        } catch (IOException ex) {
            Logger.getLogger(ChatWS.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

From source file:com.exalttech.trex.ui.views.streams.binders.BuilderDataBinding.java

License:Apache License

public String serializeAsPacketModel() {

    JsonObject model = new JsonObject();
    model.add("protocols", new JsonArray());

    JsonObject fieldEngine = new JsonObject();
    fieldEngine.add("instructions", new JsonArray());
    fieldEngine.add("global_parameters", new JsonObject());
    model.add("field_engine", fieldEngine);

    Map<String, AddressDataBinding> l3Binds = new HashMap<>();

    l3Binds.put("Ether", macDB);
    boolean isIPv4 = protocolSelection.getIpv4Property().get();
    if (isIPv4) {
        l3Binds.put("IP", ipv4DB);
    }/*from  w  w  w  .j  a v a2  s . c o  m*/

    l3Binds.entrySet().stream().forEach(entry -> {
        JsonObject proto = new JsonObject();
        String protoID = entry.getKey();
        proto.add("id", new JsonPrimitive(protoID));

        JsonArray fields = new JsonArray();

        AddressDataBinding binding = entry.getValue();
        String srcMode = entry.getValue().getDestination().getModeProperty().get();
        String dstMode = entry.getValue().getSource().getModeProperty().get();

        if (!MODE_TREX_CONFIG.equals(srcMode)) {
            fields.add(buildProtoField("src", binding.getSource().getAddressProperty().getValue()));
        }

        if (!MODE_TREX_CONFIG.equals(dstMode)) {
            fields.add(buildProtoField("dst", binding.getDestination().getAddressProperty().getValue()));
        }

        if (protoID.equals("Ether") && ethernetDB.getOverrideProperty().get()) {
            fields.add(buildProtoField("type", ethernetDB.getTypeProperty().getValue()));
        }
        proto.add("fields", fields);
        model.getAsJsonArray("protocols").add(proto);
        if (!MODE_FIXED.equals(binding.getSource().getModeProperty().get())
                && !MODE_TREX_CONFIG.equals(binding.getSource().getModeProperty().get())) {
            fieldEngine.getAsJsonArray("instructions")
                    .addAll(buildVMInstructions(protoID, "src", binding.getSource()));
        }
        if (!MODE_FIXED.equals(binding.getDestination().getModeProperty().get())
                && !MODE_TREX_CONFIG.equals(binding.getDestination().getModeProperty().get())) {
            fieldEngine.getAsJsonArray("instructions")
                    .addAll(buildVMInstructions(protoID, "dst", binding.getDestination()));
        }

    });

    boolean isVLAN = protocolSelection.getTaggedVlanProperty().get();
    String pktLenName = "pkt_len";
    String frameLenghtType = protocolSelection.getFrameLengthType();
    boolean pktSizeChanged = !frameLenghtType.equals("Fixed");
    if (pktSizeChanged) {
        LinkedHashMap<String, String> instructionParam = new LinkedHashMap<>();
        String operation = PacketBuilderHelper.getOperationFromType(frameLenghtType);
        Integer minLength = Integer.valueOf(protocolSelection.getMinLength()) - 4;
        Integer maxLength = Integer.valueOf(protocolSelection.getMaxLength()) - 4;

        instructionParam.put("init_value", minLength.toString());
        instructionParam.put("max_value", maxLength.toString());
        instructionParam.put("min_value", minLength.toString());

        instructionParam.put("name", pktLenName);
        instructionParam.put("op", operation);
        instructionParam.put("size", "2");
        instructionParam.put("step", "1");
        fieldEngine.getAsJsonArray("instructions").add(buildInstruction("STLVmFlowVar", instructionParam));

        instructionParam.clear();
        instructionParam.put("fv_name", pktLenName);
        fieldEngine.getAsJsonArray("instructions").add(buildInstruction("STLVmTrimPktSize", instructionParam));

        instructionParam.clear();
        instructionParam.put("add_val", isVLAN ? "-18" : "-14");
        instructionParam.put("is_big", "true");
        instructionParam.put("fv_name", pktLenName);
        instructionParam.put("pkt_offset", isVLAN ? "20" : "16");
        fieldEngine.getAsJsonArray("instructions").add(buildInstruction("STLVmWrFlowVar", instructionParam));
    }

    if (isVLAN) {
        JsonObject dot1QProto = new JsonObject();
        dot1QProto.add("id", new JsonPrimitive("Dot1Q"));
        Map<String, String> fieldsMap = new HashMap<>();

        fieldsMap.put("prio", vlanDB.getPriorityProperty().getValue());
        fieldsMap.put("id", vlanDB.getCfiProperty().getValue());
        fieldsMap.put("vlan", vlanDB.getVIdProperty().getValue());

        dot1QProto.add("fields", buildProtoFieldsFromMap(fieldsMap));

        JsonArray protocols = model.getAsJsonArray("protocols");
        if (protocols.size() == 2) {
            JsonElement ipv4 = protocols.get(1);
            protocols.set(1, dot1QProto);
            protocols.add(ipv4);
        } else {
            model.getAsJsonArray("protocols").add(dot1QProto);
        }

        if (vlanDB.getOverrideTPIdProperty().getValue()) {
            JsonArray etherFields = ((JsonObject) model.getAsJsonArray("protocols").get(0)).get("fields")
                    .getAsJsonArray();
            if (etherFields.size() == 3) {
                etherFields.remove(2);
            }
            etherFields.add(buildProtoField("type", vlanDB.getTpIdProperty().getValue()));
        }
    }

    boolean isTCP = protocolSelection.getTcpProperty().get();
    if (isTCP) {
        JsonObject tcpProto = new JsonObject();
        tcpProto.add("id", new JsonPrimitive("TCP"));

        Map<String, String> fieldsMap = new HashMap<>();
        fieldsMap.put("sport", tcpProtocolDB.getSrcPortProperty().getValue());
        fieldsMap.put("dport", tcpProtocolDB.getDstPortProperty().getValue());
        fieldsMap.put("chksum", "0x" + tcpProtocolDB.getChecksumProperty().getValue());
        fieldsMap.put("seq", tcpProtocolDB.getSequenceNumberProperty().getValue());
        fieldsMap.put("urgptr", tcpProtocolDB.getUrgentPointerProperty().getValue());
        fieldsMap.put("ack", tcpProtocolDB.getAckNumberProperty().getValue());

        int tcp_flags = 0;
        if (tcpProtocolDB.getUrgProperty().get()) {
            tcp_flags = tcp_flags | (1 << 5);
        }
        if (tcpProtocolDB.getAckProperty().get()) {
            tcp_flags = tcp_flags | (1 << 4);
        }
        if (tcpProtocolDB.getPshProperty().get()) {
            tcp_flags = tcp_flags | (1 << 3);
        }
        if (tcpProtocolDB.getRstProperty().get()) {
            tcp_flags = tcp_flags | (1 << 2);
        }
        if (tcpProtocolDB.getSynProperty().get()) {
            tcp_flags = tcp_flags | (1 << 1);
        }
        if (tcpProtocolDB.getFinProperty().get()) {
            tcp_flags = tcp_flags | 1;
        }
        fieldsMap.put("flags", String.valueOf(tcp_flags));

        tcpProto.add("fields", buildProtoFieldsFromMap(fieldsMap));
        model.getAsJsonArray("protocols").add(tcpProto);
    }

    // Field Engine instructions
    String cache_size = "5000";
    if ("Enable".equals(advancedPropertiesDB.getCacheSizeTypeProperty().getValue())) {
        cache_size = advancedPropertiesDB.getCacheValueProperty().getValue();
    }
    fieldEngine.getAsJsonObject("global_parameters").add("cache_size", new JsonPrimitive(cache_size));

    boolean isUDP = protocolSelection.getUdpProperty().get();
    if (isUDP) {
        JsonObject udpProto = new JsonObject();
        udpProto.add("id", new JsonPrimitive("UDP"));

        Map<String, String> fieldsMap = new HashMap<>();
        fieldsMap.put("sport", udpProtocolDB.getSrcPortProperty().getValue());
        fieldsMap.put("dport", udpProtocolDB.getDstPortProperty().getValue());
        fieldsMap.put("len", udpProtocolDB.getLengthProperty().getValue());

        udpProto.add("fields", buildProtoFieldsFromMap(fieldsMap));
        model.getAsJsonArray("protocols").add(udpProto);

        if (pktSizeChanged) {
            LinkedHashMap<String, String> instructionParam = new LinkedHashMap<>();
            instructionParam.put("add_val", isVLAN ? "-38" : "-34");
            instructionParam.put("is_big", "true");
            instructionParam.put("fv_name", pktLenName);
            instructionParam.put("pkt_offset", isVLAN ? "42" : "38");
            fieldEngine.getAsJsonArray("instructions")
                    .add(buildInstruction("STLVmWrFlowVar", instructionParam));
        }
    }

    if (ipv4DB.hasInstructions() || pktSizeChanged) {
        Map<String, String> flowWrVarParameters = new HashMap<>();
        flowWrVarParameters.put("offset", "IP");
        fieldEngine.getAsJsonArray("instructions").add(buildInstruction("STLVmFixIpv4", flowWrVarParameters));
    }

    return model.toString();
}

From source file:com.exorath.buycraftconsumer.commandHandlers.ActionAPIHandler.java

License:Apache License

@Override
public boolean handle(JsonObject command, DuePlayer duePlayer, DueCommand dueCommand) {
    try {// w  w  w.  j  a v  a 2s  .  c  o  m

        String type = command.get("type").getAsString();

        String subject = command.has("subject") ? command.get("subject").getAsString() : duePlayer.getUuid();
        String destination = command.has("destination") ? command.get("destination").getAsString() : null;
        boolean spigot = command.has("spigot") ? command.get("spigot").getAsBoolean() : true;

        JsonObject meta = command.has("meta") ? command.get("meta").getAsJsonObject() : new JsonObject();
        meta = GSON.fromJson(meta.toString().replaceAll("%NAME%", duePlayer.getName()).replaceAll("%UUID%",
                duePlayer.getUuid()), JsonObject.class);
        if (subject.equals("uuid"))
            subject = duePlayer.getUuid();
        Action action = new Action(subject, destination, type, meta, spigot);
        Success success = actionAPIServiceAPI.publishAction(action);
        if (!success.getSuccess())
            System.out.println(success.getError());
        return success.getSuccess();
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:com.facebook.ads.sdk.AdAccount.java

License:Open Source License

public static APINodeList<AdAccount> parseResponse(String json, APIContext context, APIRequest request)
        throws MalformedResponseException {
    APINodeList<AdAccount> adAccounts = new APINodeList<AdAccount>(request, json);
    JsonArray arr;//from  w w w .j a  v a  2s.  c o  m
    JsonObject obj;
    JsonParser parser = new JsonParser();
    Exception exception = null;
    try {
        JsonElement result = parser.parse(json);
        if (result.isJsonArray()) {
            // First, check if it's a pure JSON Array
            arr = result.getAsJsonArray();
            for (int i = 0; i < arr.size(); i++) {
                adAccounts.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context));
            }
            ;
            return adAccounts;
        } else if (result.isJsonObject()) {
            obj = result.getAsJsonObject();
            if (obj.has("data")) {
                if (obj.has("paging")) {
                    JsonObject paging = obj.get("paging").getAsJsonObject().get("cursors").getAsJsonObject();
                    String before = paging.has("before") ? paging.get("before").getAsString() : null;
                    String after = paging.has("after") ? paging.get("after").getAsString() : null;
                    adAccounts.setPaging(before, after);
                }
                if (obj.get("data").isJsonArray()) {
                    // Second, check if it's a JSON array with "data"
                    arr = obj.get("data").getAsJsonArray();
                    for (int i = 0; i < arr.size(); i++) {
                        adAccounts.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context));
                    }
                    ;
                } else if (obj.get("data").isJsonObject()) {
                    // Third, check if it's a JSON object with "data"
                    obj = obj.get("data").getAsJsonObject();
                    boolean isRedownload = false;
                    for (String s : new String[] { "campaigns", "adsets", "ads" }) {
                        if (obj.has(s)) {
                            isRedownload = true;
                            obj = obj.getAsJsonObject(s);
                            for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
                                adAccounts.add(loadJSON(entry.getValue().toString(), context));
                            }
                            break;
                        }
                    }
                    if (!isRedownload) {
                        adAccounts.add(loadJSON(obj.toString(), context));
                    }
                }
                return adAccounts;
            } else if (obj.has("images")) {
                // Fourth, check if it's a map of image objects
                obj = obj.get("images").getAsJsonObject();
                for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
                    adAccounts.add(loadJSON(entry.getValue().toString(), context));
                }
                return adAccounts;
            } else {
                // Fifth, check if it's an array of objects indexed by id
                boolean isIdIndexedArray = true;
                for (Map.Entry entry : obj.entrySet()) {
                    String key = (String) entry.getKey();
                    if (key.equals("__fb_trace_id__")) {
                        continue;
                    }
                    JsonElement value = (JsonElement) entry.getValue();
                    if (value != null && value.isJsonObject() && value.getAsJsonObject().has("id")
                            && value.getAsJsonObject().get("id") != null
                            && value.getAsJsonObject().get("id").getAsString().equals(key)) {
                        adAccounts.add(loadJSON(value.toString(), context));
                    } else {
                        isIdIndexedArray = false;
                        break;
                    }
                }
                if (isIdIndexedArray) {
                    return adAccounts;
                }

                // Sixth, check if it's pure JsonObject
                adAccounts.clear();
                adAccounts.add(loadJSON(json, context));
                return adAccounts;
            }
        }
    } catch (Exception e) {
        exception = e;
    }
    throw new MalformedResponseException("Invalid response string: " + json, exception);
}

From source file:com.facebook.ads.sdk.AdAccountDeliveryEstimate.java

License:Open Source License

public static APINodeList<AdAccountDeliveryEstimate> parseResponse(String json, APIContext context,
        APIRequest request) throws MalformedResponseException {
    APINodeList<AdAccountDeliveryEstimate> adAccountDeliveryEstimates = new APINodeList<AdAccountDeliveryEstimate>(
            request, json);//  w  ww .  j  a v a2 s.com
    JsonArray arr;
    JsonObject obj;
    JsonParser parser = new JsonParser();
    Exception exception = null;
    try {
        JsonElement result = parser.parse(json);
        if (result.isJsonArray()) {
            // First, check if it's a pure JSON Array
            arr = result.getAsJsonArray();
            for (int i = 0; i < arr.size(); i++) {
                adAccountDeliveryEstimates.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context));
            }
            ;
            return adAccountDeliveryEstimates;
        } else if (result.isJsonObject()) {
            obj = result.getAsJsonObject();
            if (obj.has("data")) {
                if (obj.has("paging")) {
                    JsonObject paging = obj.get("paging").getAsJsonObject().get("cursors").getAsJsonObject();
                    String before = paging.has("before") ? paging.get("before").getAsString() : null;
                    String after = paging.has("after") ? paging.get("after").getAsString() : null;
                    adAccountDeliveryEstimates.setPaging(before, after);
                }
                if (obj.get("data").isJsonArray()) {
                    // Second, check if it's a JSON array with "data"
                    arr = obj.get("data").getAsJsonArray();
                    for (int i = 0; i < arr.size(); i++) {
                        adAccountDeliveryEstimates
                                .add(loadJSON(arr.get(i).getAsJsonObject().toString(), context));
                    }
                    ;
                } else if (obj.get("data").isJsonObject()) {
                    // Third, check if it's a JSON object with "data"
                    obj = obj.get("data").getAsJsonObject();
                    boolean isRedownload = false;
                    for (String s : new String[] { "campaigns", "adsets", "ads" }) {
                        if (obj.has(s)) {
                            isRedownload = true;
                            obj = obj.getAsJsonObject(s);
                            for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
                                adAccountDeliveryEstimates.add(loadJSON(entry.getValue().toString(), context));
                            }
                            break;
                        }
                    }
                    if (!isRedownload) {
                        adAccountDeliveryEstimates.add(loadJSON(obj.toString(), context));
                    }
                }
                return adAccountDeliveryEstimates;
            } else if (obj.has("images")) {
                // Fourth, check if it's a map of image objects
                obj = obj.get("images").getAsJsonObject();
                for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
                    adAccountDeliveryEstimates.add(loadJSON(entry.getValue().toString(), context));
                }
                return adAccountDeliveryEstimates;
            } else {
                // Fifth, check if it's an array of objects indexed by id
                boolean isIdIndexedArray = true;
                for (Map.Entry entry : obj.entrySet()) {
                    String key = (String) entry.getKey();
                    if (key.equals("__fb_trace_id__")) {
                        continue;
                    }
                    JsonElement value = (JsonElement) entry.getValue();
                    if (value != null && value.isJsonObject() && value.getAsJsonObject().has("id")
                            && value.getAsJsonObject().get("id") != null
                            && value.getAsJsonObject().get("id").getAsString().equals(key)) {
                        adAccountDeliveryEstimates.add(loadJSON(value.toString(), context));
                    } else {
                        isIdIndexedArray = false;
                        break;
                    }
                }
                if (isIdIndexedArray) {
                    return adAccountDeliveryEstimates;
                }

                // Sixth, check if it's pure JsonObject
                adAccountDeliveryEstimates.clear();
                adAccountDeliveryEstimates.add(loadJSON(json, context));
                return adAccountDeliveryEstimates;
            }
        }
    } catch (Exception e) {
        exception = e;
    }
    throw new MalformedResponseException("Invalid response string: " + json, exception);
}

From source file:com.facebook.ads.sdk.AdAccountGroup.java

License:Open Source License

public static APINodeList<AdAccountGroup> parseResponse(String json, APIContext context, APIRequest request)
        throws MalformedResponseException {
    APINodeList<AdAccountGroup> adAccountGroups = new APINodeList<AdAccountGroup>(request, json);
    JsonArray arr;//  w  w  w .ja va2s  .  c  o m
    JsonObject obj;
    JsonParser parser = new JsonParser();
    Exception exception = null;
    try {
        JsonElement result = parser.parse(json);
        if (result.isJsonArray()) {
            // First, check if it's a pure JSON Array
            arr = result.getAsJsonArray();
            for (int i = 0; i < arr.size(); i++) {
                adAccountGroups.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context));
            }
            ;
            return adAccountGroups;
        } else if (result.isJsonObject()) {
            obj = result.getAsJsonObject();
            if (obj.has("data")) {
                if (obj.has("paging")) {
                    JsonObject paging = obj.get("paging").getAsJsonObject().get("cursors").getAsJsonObject();
                    String before = paging.has("before") ? paging.get("before").getAsString() : null;
                    String after = paging.has("after") ? paging.get("after").getAsString() : null;
                    adAccountGroups.setPaging(before, after);
                }
                if (obj.get("data").isJsonArray()) {
                    // Second, check if it's a JSON array with "data"
                    arr = obj.get("data").getAsJsonArray();
                    for (int i = 0; i < arr.size(); i++) {
                        adAccountGroups.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context));
                    }
                    ;
                } else if (obj.get("data").isJsonObject()) {
                    // Third, check if it's a JSON object with "data"
                    obj = obj.get("data").getAsJsonObject();
                    boolean isRedownload = false;
                    for (String s : new String[] { "campaigns", "adsets", "ads" }) {
                        if (obj.has(s)) {
                            isRedownload = true;
                            obj = obj.getAsJsonObject(s);
                            for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
                                adAccountGroups.add(loadJSON(entry.getValue().toString(), context));
                            }
                            break;
                        }
                    }
                    if (!isRedownload) {
                        adAccountGroups.add(loadJSON(obj.toString(), context));
                    }
                }
                return adAccountGroups;
            } else if (obj.has("images")) {
                // Fourth, check if it's a map of image objects
                obj = obj.get("images").getAsJsonObject();
                for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
                    adAccountGroups.add(loadJSON(entry.getValue().toString(), context));
                }
                return adAccountGroups;
            } else {
                // Fifth, check if it's an array of objects indexed by id
                boolean isIdIndexedArray = true;
                for (Map.Entry entry : obj.entrySet()) {
                    String key = (String) entry.getKey();
                    if (key.equals("__fb_trace_id__")) {
                        continue;
                    }
                    JsonElement value = (JsonElement) entry.getValue();
                    if (value != null && value.isJsonObject() && value.getAsJsonObject().has("id")
                            && value.getAsJsonObject().get("id") != null
                            && value.getAsJsonObject().get("id").getAsString().equals(key)) {
                        adAccountGroups.add(loadJSON(value.toString(), context));
                    } else {
                        isIdIndexedArray = false;
                        break;
                    }
                }
                if (isIdIndexedArray) {
                    return adAccountGroups;
                }

                // Sixth, check if it's pure JsonObject
                adAccountGroups.clear();
                adAccountGroups.add(loadJSON(json, context));
                return adAccountGroups;
            }
        }
    } catch (Exception e) {
        exception = e;
    }
    throw new MalformedResponseException("Invalid response string: " + json, exception);
}

From source file:com.facebook.ads.sdk.AdAccountGroupResult.java

License:Open Source License

public static APINodeList<AdAccountGroupResult> parseResponse(String json, APIContext context,
        APIRequest request) throws MalformedResponseException {
    APINodeList<AdAccountGroupResult> adAccountGroupResults = new APINodeList<AdAccountGroupResult>(request,
            json);//from   w  w  w . j ava2 s .  c o  m
    JsonArray arr;
    JsonObject obj;
    JsonParser parser = new JsonParser();
    Exception exception = null;
    try {
        JsonElement result = parser.parse(json);
        if (result.isJsonArray()) {
            // First, check if it's a pure JSON Array
            arr = result.getAsJsonArray();
            for (int i = 0; i < arr.size(); i++) {
                adAccountGroupResults.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context));
            }
            ;
            return adAccountGroupResults;
        } else if (result.isJsonObject()) {
            obj = result.getAsJsonObject();
            if (obj.has("data")) {
                if (obj.has("paging")) {
                    JsonObject paging = obj.get("paging").getAsJsonObject().get("cursors").getAsJsonObject();
                    String before = paging.has("before") ? paging.get("before").getAsString() : null;
                    String after = paging.has("after") ? paging.get("after").getAsString() : null;
                    adAccountGroupResults.setPaging(before, after);
                }
                if (obj.get("data").isJsonArray()) {
                    // Second, check if it's a JSON array with "data"
                    arr = obj.get("data").getAsJsonArray();
                    for (int i = 0; i < arr.size(); i++) {
                        adAccountGroupResults.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context));
                    }
                    ;
                } else if (obj.get("data").isJsonObject()) {
                    // Third, check if it's a JSON object with "data"
                    obj = obj.get("data").getAsJsonObject();
                    boolean isRedownload = false;
                    for (String s : new String[] { "campaigns", "adsets", "ads" }) {
                        if (obj.has(s)) {
                            isRedownload = true;
                            obj = obj.getAsJsonObject(s);
                            for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
                                adAccountGroupResults.add(loadJSON(entry.getValue().toString(), context));
                            }
                            break;
                        }
                    }
                    if (!isRedownload) {
                        adAccountGroupResults.add(loadJSON(obj.toString(), context));
                    }
                }
                return adAccountGroupResults;
            } else if (obj.has("images")) {
                // Fourth, check if it's a map of image objects
                obj = obj.get("images").getAsJsonObject();
                for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
                    adAccountGroupResults.add(loadJSON(entry.getValue().toString(), context));
                }
                return adAccountGroupResults;
            } else {
                // Fifth, check if it's an array of objects indexed by id
                boolean isIdIndexedArray = true;
                for (Map.Entry entry : obj.entrySet()) {
                    String key = (String) entry.getKey();
                    if (key.equals("__fb_trace_id__")) {
                        continue;
                    }
                    JsonElement value = (JsonElement) entry.getValue();
                    if (value != null && value.isJsonObject() && value.getAsJsonObject().has("id")
                            && value.getAsJsonObject().get("id") != null
                            && value.getAsJsonObject().get("id").getAsString().equals(key)) {
                        adAccountGroupResults.add(loadJSON(value.toString(), context));
                    } else {
                        isIdIndexedArray = false;
                        break;
                    }
                }
                if (isIdIndexedArray) {
                    return adAccountGroupResults;
                }

                // Sixth, check if it's pure JsonObject
                adAccountGroupResults.clear();
                adAccountGroupResults.add(loadJSON(json, context));
                return adAccountGroupResults;
            }
        }
    } catch (Exception e) {
        exception = e;
    }
    throw new MalformedResponseException("Invalid response string: " + json, exception);
}

From source file:com.facebook.ads.sdk.AdAccountRoas.java

License:Open Source License

public static APINodeList<AdAccountRoas> parseResponse(String json, APIContext context, APIRequest request)
        throws MalformedResponseException {
    APINodeList<AdAccountRoas> adAccountRoass = new APINodeList<AdAccountRoas>(request, json);
    JsonArray arr;/*ww  w .ja  va 2  s  .co m*/
    JsonObject obj;
    JsonParser parser = new JsonParser();
    Exception exception = null;
    try {
        JsonElement result = parser.parse(json);
        if (result.isJsonArray()) {
            // First, check if it's a pure JSON Array
            arr = result.getAsJsonArray();
            for (int i = 0; i < arr.size(); i++) {
                adAccountRoass.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context));
            }
            ;
            return adAccountRoass;
        } else if (result.isJsonObject()) {
            obj = result.getAsJsonObject();
            if (obj.has("data")) {
                if (obj.has("paging")) {
                    JsonObject paging = obj.get("paging").getAsJsonObject().get("cursors").getAsJsonObject();
                    String before = paging.has("before") ? paging.get("before").getAsString() : null;
                    String after = paging.has("after") ? paging.get("after").getAsString() : null;
                    adAccountRoass.setPaging(before, after);
                }
                if (obj.get("data").isJsonArray()) {
                    // Second, check if it's a JSON array with "data"
                    arr = obj.get("data").getAsJsonArray();
                    for (int i = 0; i < arr.size(); i++) {
                        adAccountRoass.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context));
                    }
                    ;
                } else if (obj.get("data").isJsonObject()) {
                    // Third, check if it's a JSON object with "data"
                    obj = obj.get("data").getAsJsonObject();
                    boolean isRedownload = false;
                    for (String s : new String[] { "campaigns", "adsets", "ads" }) {
                        if (obj.has(s)) {
                            isRedownload = true;
                            obj = obj.getAsJsonObject(s);
                            for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
                                adAccountRoass.add(loadJSON(entry.getValue().toString(), context));
                            }
                            break;
                        }
                    }
                    if (!isRedownload) {
                        adAccountRoass.add(loadJSON(obj.toString(), context));
                    }
                }
                return adAccountRoass;
            } else if (obj.has("images")) {
                // Fourth, check if it's a map of image objects
                obj = obj.get("images").getAsJsonObject();
                for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
                    adAccountRoass.add(loadJSON(entry.getValue().toString(), context));
                }
                return adAccountRoass;
            } else {
                // Fifth, check if it's an array of objects indexed by id
                boolean isIdIndexedArray = true;
                for (Map.Entry entry : obj.entrySet()) {
                    String key = (String) entry.getKey();
                    if (key.equals("__fb_trace_id__")) {
                        continue;
                    }
                    JsonElement value = (JsonElement) entry.getValue();
                    if (value != null && value.isJsonObject() && value.getAsJsonObject().has("id")
                            && value.getAsJsonObject().get("id") != null
                            && value.getAsJsonObject().get("id").getAsString().equals(key)) {
                        adAccountRoass.add(loadJSON(value.toString(), context));
                    } else {
                        isIdIndexedArray = false;
                        break;
                    }
                }
                if (isIdIndexedArray) {
                    return adAccountRoass;
                }

                // Sixth, check if it's pure JsonObject
                adAccountRoass.clear();
                adAccountRoass.add(loadJSON(json, context));
                return adAccountRoass;
            }
        }
    } catch (Exception e) {
        exception = e;
    }
    throw new MalformedResponseException("Invalid response string: " + json, exception);
}

From source file:com.facebook.ads.sdk.AdAccountRoasCohorts.java

License:Open Source License

public static APINodeList<AdAccountRoasCohorts> parseResponse(String json, APIContext context,
        APIRequest request) {//www . j a  v a2 s.  c om
    APINodeList<AdAccountRoasCohorts> adAccountRoasCohortss = new APINodeList<AdAccountRoasCohorts>(request,
            json);
    JsonArray arr;
    JsonObject obj;
    JsonParser parser = new JsonParser();
    try {
        JsonElement result = parser.parse(json);
        if (result.isJsonArray()) {
            // First, check if it's a pure JSON Array
            arr = result.getAsJsonArray();
            for (int i = 0; i < arr.size(); i++) {
                adAccountRoasCohortss.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context));
            }
            ;
            return adAccountRoasCohortss;
        } else if (result.isJsonObject()) {
            obj = result.getAsJsonObject();
            if (obj.has("data")) {
                try {
                    JsonObject paging = obj.get("paging").getAsJsonObject().get("cursors").getAsJsonObject();
                    adAccountRoasCohortss.setPaging(paging.get("before").getAsString(),
                            paging.get("after").getAsString());
                } catch (Exception ignored) {
                }
                if (obj.get("data").isJsonArray()) {
                    // Second, check if it's a JSON array with "data"
                    arr = obj.get("data").getAsJsonArray();
                    for (int i = 0; i < arr.size(); i++) {
                        adAccountRoasCohortss.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context));
                    }
                    ;
                } else if (obj.get("data").isJsonObject()) {
                    // Third, check if it's a JSON object with "data"
                    obj = obj.get("data").getAsJsonObject();
                    adAccountRoasCohortss.add(loadJSON(obj.toString(), context));
                }
                return adAccountRoasCohortss;
            } else if (obj.has("images")) {
                // Fourth, check if it's a map of image objects
                obj = obj.get("images").getAsJsonObject();
                for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
                    adAccountRoasCohortss.add(loadJSON(entry.getValue().toString(), context));
                }
                return adAccountRoasCohortss;
            } else {
                // Fifth, check if it's pure JsonObject
                adAccountRoasCohortss.add(loadJSON(json, context));
                return adAccountRoasCohortss;
            }
        }
    } catch (Exception e) {
    }
    return null;
}

From source file:com.facebook.ads.sdk.AdAccountTargetingBrowse.java

License:Open Source License

public static APINodeList<AdAccountTargetingBrowse> parseResponse(String json, APIContext context,
        APIRequest request) {/*  ww  w.  j  ava 2  s  .  co m*/
    APINodeList<AdAccountTargetingBrowse> adAccountTargetingBrowses = new APINodeList<AdAccountTargetingBrowse>(
            request, json);
    JsonArray arr;
    JsonObject obj;
    JsonParser parser = new JsonParser();
    try {
        JsonElement result = parser.parse(json);
        if (result.isJsonArray()) {
            // First, check if it's a pure JSON Array
            arr = result.getAsJsonArray();
            for (int i = 0; i < arr.size(); i++) {
                adAccountTargetingBrowses.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context));
            }
            ;
            return adAccountTargetingBrowses;
        } else if (result.isJsonObject()) {
            obj = result.getAsJsonObject();
            if (obj.has("data")) {
                try {
                    JsonObject paging = obj.get("paging").getAsJsonObject().get("cursors").getAsJsonObject();
                    adAccountTargetingBrowses.setPaging(paging.get("before").getAsString(),
                            paging.get("after").getAsString());
                } catch (Exception ignored) {
                }
                if (obj.get("data").isJsonArray()) {
                    // Second, check if it's a JSON array with "data"
                    arr = obj.get("data").getAsJsonArray();
                    for (int i = 0; i < arr.size(); i++) {
                        adAccountTargetingBrowses
                                .add(loadJSON(arr.get(i).getAsJsonObject().toString(), context));
                    }
                    ;
                } else if (obj.get("data").isJsonObject()) {
                    // Third, check if it's a JSON object with "data"
                    obj = obj.get("data").getAsJsonObject();
                    adAccountTargetingBrowses.add(loadJSON(obj.toString(), context));
                }
                return adAccountTargetingBrowses;
            } else if (obj.has("images")) {
                // Fourth, check if it's a map of image objects
                obj = obj.get("images").getAsJsonObject();
                for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
                    adAccountTargetingBrowses.add(loadJSON(entry.getValue().toString(), context));
                }
                return adAccountTargetingBrowses;
            } else {
                // Fifth, check if it's pure JsonObject
                adAccountTargetingBrowses.add(loadJSON(json, context));
                return adAccountTargetingBrowses;
            }
        }
    } catch (Exception e) {
    }
    return null;
}