Example usage for com.google.gson JsonElement toString

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

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Returns a String representation of this element.

Usage

From source file:com.crypticbit.diff.demo.swing.JSONJTreeNode.java

License:Apache License

/**
 * @param fieldName/*from   w ww  .  j a va2 s  . c o  m*/
 *            - name of field if applicable or null
 * @param index
 *            - index of element in the array or -1 if not part of an array
 * @param jsonElement
 *            - element to represent
 */
public JSONJTreeNode(String fieldName, int index, JsonElement jsonElement) {
    this.index = index;
    this.fieldName = fieldName;
    if (jsonElement.isJsonArray()) {
        this.dataType = DataType.ARRAY;
        this.value = jsonElement.toString();
        populateChildren(jsonElement);
    } else if (jsonElement.isJsonObject()) {
        this.dataType = DataType.OBJECT;
        this.value = jsonElement.toString();
        populateChildren(jsonElement);
    } else if (jsonElement.isJsonPrimitive()) {
        this.dataType = DataType.VALUE;
        this.value = jsonElement.toString();
    } else if (jsonElement.isJsonNull()) {
        this.dataType = DataType.VALUE;
        this.value = jsonElement.toString();
    } else {
        throw new IllegalArgumentException("jsonElement is an unknown element type.");
    }

}

From source file:com.crypticbit.diff.demo.swing.JSONJTreeNode.java

License:Apache License

@SuppressWarnings("unchecked")
private void buildJsonString(StringBuilder sb) {
    if (!(this.fieldName == null || this.fieldName.length() == 0)) {
        sb.append("\"" + this.fieldName + "\":");
    }//from  www  .  ja  v  a  2 s . c  om
    Enumeration children;
    switch (dataType) {
    case ARRAY:
        sb.append("[");
        children = this.children();
        while (children.hasMoreElements()) {
            JSONJTreeNode child = (JSONJTreeNode) children.nextElement();
            child.buildJsonString(sb);
            if (children.hasMoreElements()) {
                sb.append(",");
            }
        }
        sb.append("]");
        break;
    case OBJECT:
        sb.append("{");
        children = this.children();
        while (children.hasMoreElements()) {
            JSONJTreeNode child = (JSONJTreeNode) children.nextElement();
            child.buildJsonString(sb);
            if (children.hasMoreElements()) {
                sb.append(",");
            }
        }
        sb.append("}");
        break;
    default: {
        // Use the JSON parser to parse the value for safety
        JsonElement elt = new JsonParser().parse(this.value);
        sb.append(elt.toString());
    }
    }
}

From source file:com.daking.sports.api.HttpLoggingInterceptor.java

License:Apache License

private String format2UTF8(String text) {
    try {/*from  w  w w.  ja  v a  2 s  . c om*/
        JsonElement jsonElement = new JsonParser().parse(text);
        return jsonElement.toString();
    } catch (Exception e) {
        return text;
    }
}

From source file:com.doitnext.swing.widgets.json.JSONJTreeNode.java

License:Apache License

@SuppressWarnings("unchecked")
private void buildJsonString(StringBuilder sb) {
    if (!StringUtils.isEmpty(this.fieldName)) {
        sb.append("\"" + this.fieldName + "\":");
    }/*from w  w  w.j  av  a  2s .  c o m*/
    Enumeration children;
    switch (dataType) {
    case ARRAY:
        sb.append("[");
        children = this.children();
        while (children.hasMoreElements()) {
            JSONJTreeNode child = (JSONJTreeNode) children.nextElement();
            child.buildJsonString(sb);
            if (children.hasMoreElements())
                sb.append(",");
        }
        sb.append("]");
        break;
    case OBJECT:
        sb.append("{");
        children = this.children();
        while (children.hasMoreElements()) {
            JSONJTreeNode child = (JSONJTreeNode) children.nextElement();
            child.buildJsonString(sb);
            if (children.hasMoreElements())
                sb.append(",");
        }
        sb.append("}");
        break;
    default: {
        // Use the JSON parser to parse the value for safety
        JsonElement elt = new JsonParser().parse(this.value);
        sb.append(elt.toString());
    }
    }
}

From source file:com.dozersoftware.snap.PosRepProcessor.java

License:Open Source License

public Message http(Message message) throws ActionProcessingException {

    System.out.println("&&&&&&&&&&&&&&&& PosRepProcessor &&&&&&&&&&&&&&&&&&&&&");
    System.out.println("");
    System.out.println("Service: " + service);
    System.out.println("");
    // System.out.println("------------Http Request Info (XStream Encoded)-------------------");
    // HttpRequest requestInfo = HttpRequest.getRequest(message);
    // String requestInfoXML;

    // XStream xstream = new XStream();
    // requestInfoXML = xstream.toXML(requestInfo);

    // System.out.println(requestInfoXML);

    System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");

    try {//  w  ww. jav a2  s .  c om
        StringWriter sw = new StringWriter();
        final Kml kml = new Kml();
        Map<URI, Message> msgs = messageStore.getAllMessages("PosRep");
        Iterator<URI> it = msgs.keySet().iterator();
        System.out.println("Tracking for :" + msgs.size() + " records");
        while (it.hasNext()) {
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            String raw = (String) msgs.get(it.next()).getBody().get();

            Document doc = dBuilder.parse(new ByteArrayInputStream(raw.getBytes()));

            doc.getDocumentElement().normalize();
            NodeList body = doc.getElementsByTagName("BODY");
            String handle = doc.getDocumentElement().getAttribute("sender");
            Node e = body.item(0);
            System.out.println("SNAP: " + handle + "'s PosRep -> " + e.getTextContent());
            JsonElement jse = new JsonParser().parse(e.getTextContent());
            if (jse.isJsonObject()) {
                System.out.println("We got the right thing: " + jse.toString());
                JsonArray ja = jse.getAsJsonObject().getAsJsonArray("POSREP");
                // {"POSREP":
                // [16,"Aug 17, 2010 3:11:00 AM","31.74","-111.11"]}
                Double lat = ja.get(2).getAsDouble();
                Double lng = ja.get(3).getAsDouble();

                kml.createAndSetPlacemark().withName(handle).withOpen(Boolean.TRUE).createAndSetPoint()
                        .addToCoordinates(lng, lat);
            } else {
                System.out.println("Not an Array!");
            }

        }

        System.out.println("Processed all positions...");
        kml.marshal(sw);

        message.getBody().add(sw.toString());
    } catch (DOMException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JsonParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessageStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return message;

}

From source file:com.ecwid.mailchimp.MailChimpClient.java

License:Apache License

private JsonElement execute(String url, JsonElement request) throws IOException {
    return new JsonParser().parse(execute(url, request.toString()));
}

From source file:com.epam.wilma.sequence.formatters.SequenceAwareJsonTemplateFormatter.java

License:Open Source License

@Override
public byte[] formatTemplate(final WilmaHttpRequest wilmaRequest, final HttpServletResponse resp,
        final byte[] templateResource, final ParameterList params) throws Exception {
    JsonElement response = new JsonParser()
            .parse(IOUtils.toString(templateResource, StandardCharsets.UTF_8.name()));
    new SessionAwareJsonTreeEvaluator(wilmaRequest.getBody(), wilmaRequest.getSequence(), params)
            .replaceAllNonRecursive(response);

    return response.toString().getBytes();
}

From source file:com.epam.wilma.webapp.stub.response.formatter.json.JsonTemplateFormatter.java

License:Open Source License

@Override
public byte[] formatTemplate(final WilmaHttpRequest wilmaRequest, final HttpServletResponse resp,
        final byte[] templateResource, final ParameterList params) throws Exception {
    JsonElement response = new JsonParser().parse(new String(templateResource, StandardCharsets.UTF_8));

    new NonRecursiveJsonTreeEvaluator(wilmaRequest.getBody()).replaceAllNonRecursive(response);

    return response.toString().getBytes();
}

From source file:com.ericsson.eiffel.remrem.publish.service.MessageServiceRMQImpl.java

License:Apache License

@Override
public SendResult send(String jsonContent, MsgService msgService, String userDomainSuffix, String tag,
        String routingKey) {// w ww  .  j av a  2s .  co m

    JsonParser parser = new JsonParser();
    try {
        JsonElement json = parser.parse(jsonContent);
        if (json.isJsonArray()) {
            return send(json, msgService, userDomainSuffix, tag, routingKey);
        } else {
            Map<String, String> map = new HashMap<>();
            Map<String, String> routingKeyMap = new HashMap<>();
            String eventId = msgService.getEventId(json.getAsJsonObject());
            if (StringUtils.isNotBlank(eventId)) {
                String routing_key = PublishUtils.getRoutingKey(msgService, json.getAsJsonObject(), rmqHelper,
                        userDomainSuffix, tag, routingKey);
                if (StringUtils.isNotBlank(routing_key)) {
                    map.put(eventId, json.toString());
                    routingKeyMap.put(eventId, routing_key);
                } else if (routing_key == null) {
                    List<PublishResultItem> resultItemList = new ArrayList<>();
                    routingKeyGenerationFailure(resultItemList);
                    return new SendResult(resultItemList);
                } else {
                    List<PublishResultItem> resultItemList = new ArrayList<>();
                    PublishResultItem resultItem = rabbitmqConfigurationNotFound(msgService);
                    resultItemList.add(resultItem);
                    return new SendResult(resultItemList);
                }
            } else {
                List<PublishResultItem> resultItemList = new ArrayList<>();
                createFailureResult(resultItemList);
                return new SendResult(resultItemList);
            }
            return send(routingKeyMap, map, msgService);
        }
    } catch (final JsonSyntaxException e) {
        String resultMsg = "Could not parse JSON.";
        if (e.getCause() != null) {
            resultMsg = resultMsg + " Cause: " + e.getCause().getMessage();
        }
        log.error(resultMsg, e.getMessage());
        List<PublishResultItem> resultItemList = new ArrayList<>();
        createFailureResult(resultItemList);
        return new SendResult(resultItemList);
    }
}

From source file:com.ericsson.eiffel.remrem.publish.service.MessageServiceRMQImpl.java

License:Apache License

@Override
public SendResult send(JsonElement json, MsgService msgService, String userDomainSuffix, String tag,
        String routingKey) {// w ww  .  j  a v a 2s.  c  o  m
    Map<String, String> map = new HashMap<>();
    Map<String, String> routingKeyMap = new HashMap<>();
    SendResult result;
    resultList = new ArrayList<PublishResultItem>();
    if (json == null) {
        createFailureResult(resultList);
    }
    if (json.isJsonArray()) {
        statusCodes = new ArrayList<Integer>();
        checkEventStatus = true;
        JsonArray bodyJson = json.getAsJsonArray();
        for (JsonElement obj : bodyJson) {
            String eventId = msgService.getEventId(obj.getAsJsonObject());
            if (StringUtils.isNotEmpty(eventId) && checkEventStatus) {
                String routing_key = getAndCheckEvent(msgService, map, resultList, obj, routingKeyMap,
                        userDomainSuffix, tag, routingKey);
                if (StringUtils.isNotBlank(routing_key)) {
                    result = send(obj.toString(), msgService, userDomainSuffix, tag, routing_key);
                    resultList.addAll(result.getEvents());
                    int statusCode = result.getEvents().get(0).getStatusCode();
                    if (!statusCodes.contains(statusCode))
                        statusCodes.add(statusCode);
                } else if (routing_key == null) {
                    routingKeyGenerationFailure(resultList);
                    errorItems = new ArrayList<JsonElement>();
                    int statusCode = resultList.get(0).getStatusCode();
                    statusCodes.add(statusCode);
                    errorItems.add(obj);
                    checkEventStatus = false;
                } else {
                    PublishResultItem resultItem = rabbitmqConfigurationNotFound(msgService);
                    resultList.add(resultItem);
                    int statusCode = resultItem.getStatusCode();
                    statusCodes.add(statusCode);
                    break;
                }
            } else {
                if (!checkEventStatus) {
                    addUnsuccessfulResultItem(obj);
                    int statusCode = resultList.get(0).getStatusCode();
                    statusCodes.add(statusCode);
                } else {
                    createFailureResult(resultList);
                    errorItems = new ArrayList<JsonElement>();
                    int statusCode = resultList.get(0).getStatusCode();
                    statusCodes.add(statusCode);
                    errorItems.add(obj);
                    checkEventStatus = false;
                }
            }
        }
    } else {
        statusCodes = new ArrayList<Integer>();
        result = send(json.toString(), msgService, userDomainSuffix, tag, routingKey);
        resultList.addAll(result.getEvents());
        int statusCode = result.getEvents().get(0).getStatusCode();
        if (!statusCodes.contains(statusCode))
            statusCodes.add(statusCode);
    }
    result = new SendResult();
    result.setEvents(resultList);
    return result;
}