Showing posts with label Xml Parsing. Show all posts
Showing posts with label Xml Parsing. Show all posts

Friday, August 4, 2017

Parse the JSON Response in Salesforce Apex -Part 2

In this post I'm going to explain how to create a wrapper class in apex to parse the JSON response which having multiple key value pairs only.

JSON String:


{
    "AccID1" : {
        "contacts" : {
            "0055be4ce5802020100" : "CREATED",
            "0055be4ce5802020100" : "Open"
        },
  "cs" : {
            "f0055be4ce5802020100" : "CREATED",
            "09055be4ce5802020100" : "Completed"
        }
    },
    "AccID2" : {
        "contacts" : {
            "0055be4ce5802020100" : "SUCCESSFUL"
        }
    },
    "AccID3" : {
        "contacts" : {
            "0055be4ce5801020100" : "CREATED"
        },
        "cs" : {
            "f0055be4ce5802030100" : "Open",
            "f0055be4ce5802030100" : "Re-Open",
            "f0055be4ce5802030100" : "Closed"
        }
    },
 "AccID4" : {
        "contacts" : {
            "0055be4ce5801020100" : "Initiated"
        }
       
    }
}

Apex Class:

//Wrapper Class For Parsering 
public class ParsingTest
{
  public ParsingTest()
  {
        String jsonString='Pass your JSON String Here';
 Map<string,ContactsCSWrapper> apiRespone = new Map<string,ContactsCSWrapper>();
 apiRespone = (Map<string,ContactsCSWrapper>)System.JSON.deserialize(jsonString,Map<string,ContactsCSWrapper>.class);
 System.debug('apiRespone..'+apiRespone.keySet()); //Outputs AccID1,AccID2,AccID3,AccID4
  }
  
  public class ContactsCSWrapper 
 {
  public map<string, string> cs { get; set; }
  public map<string, string> contacts { get; set; }
 }
}


Hope this helps you....Enjoy!

Parse the JSON Response in Salesforce Apex -Part 1

In this post I'm going to explain how to create a Wrapper class to Parse the JSON Response in Apex which contains key and value pair in JSON.

JSON String:

{
 "status": "SUCCESS",
 "errors": [],
 "data": {
  "oldCaseStatus": "Case_CANCELLATION_success",
  "newCaseStatus": "Case_CANCELLATION_success",
  "NewCaseNumber": "3732gy12"
         }
}

Apex Class:

public class ParsingTest
{
  public ParsingTest()
  {
      String json='{"status":"SUCCESS","errors":[],"data":{"oldCaseStatus":"Case_CANCELLATION_success","newCaseStatus":"Case_CANCELLATION_success","NewCaseNumber":"3732gy12"}}';
      ParsingWrapper apiRespone = new ParsingWrapper();
      
      apiRespone = (ParsingWrapper)System.JSON.deserialize(json,ParsingWrapper.class);
      System.debug('apiRespone..'+apiRespone);
  }

 //Wrapper Class For Parsering 

  public class ParsingWrapper
  {
   public String status{get;set;}
   public Map<String,String> data{get;set;}
   public Cls_errors[] errors;
  }

  public class Cls_errors
  {

  }
}


Hope this helps you....Enjoy!

Friday, September 27, 2013

Most Important OnLine Tool for Coding and Decoding(i.e.,For Conversion)

Coder's Tool Box:

The Coder’s Toolbox contains all the little tools you never know where to find.
  • Time conversion – convert between Unix timestamp, ISO8601 and RFC 2822 formats
  • String conversion – encode/decode Base64-encoding; escape XML, URL's and ECMAScript; translate to UTF-8
  • Number conversion – convert between decimal, hexadecimal, octal and binary numbers
  • Network – calculate netmasks, broadcast addresses and do DNS lookups
  • Bandwidth – calculate the duration of file transfer
  • XPath debugger – test your XPath expressions
For more information please visit the below link

http://coderstoolbox.net/string/#!encoding=base64&action=encode&charset=iso_8859_1

Monday, September 23, 2013

XML NameSpaces in SalesForce

XML NameSpaces:
An XML namespace is a collection of names identified by a URI reference and used in XML documents to uniquely identify element types and attribute names. Names in XML namespaces may appear as qualified names, which contain a single colon, separating the name into a namespace prefix and a local part. The prefix, which is mapped to a URI reference, selects a namespace. The combination of the universally managed URI namespace and the document's own namespace produces identifiers that are universally unique.
The following XML element has a namespace of http://my.name.space and a prefix of myprefix.
<sampleElement xmlns:myprefix="http://my.name.space" />
  In the following example, the XML element has two attributes:
  • The first attribute has a key of dimension; the value is 2.
  • The second attribute has a key namespace of http://ns1; the value namespace is http://ns2; the key is foo; the value is bar.
<square dimension="2" ns1:foo="ns2:bar" xmlns:ns1="http://ns1" xmlns:ns2="http://ns2" />

 For more information regarding XML Namespaces Please visit the below link
 http://www.xmlmaster.org/en/article/d01/c10/

Friday, September 20, 2013

Document Class in Salesforce

Document Class:


Use the Document class to process XML content. One common application is to use it to create the body of a request for HttpRequest or to parse a response accessed by HttpResponse.


Methods

The Document class has the following methods:
NameArgumentsReturn TypeDescription
createRootElementString name
String namespace
String prefix
Dom.XmlNodeCreates the top-level root element for a document.
The name argument can't have a null value.
If the namespace argument has a non-null value and the prefix argument is null, the namespace is set as the default namespace.
If the prefix argument is nullSalesforce automatically assigns a prefix for the element. The format of the automatic prefix is nsi, where i is a number.
If the prefix argument is '', the namespace is set as the default namespace.
For more information about namespaces, see XML Namespaces.
Calling this method more than once on a document generates an error as a document can have only one root element.
getRootElementDom.XmlNodeReturns the top-level root element node in the document. If this method returns null, the root element has not been created yet.
loadString xmlVoidParse the XML representation of the document specified in the xml argument and load it into a document. For example:
Dom.Document doc = new Dom.Document();
doc.load(xml);
toXmlStringStringReturns the XML representation of the document as a String.



Example:

For the purposes of the sample below, assume that the url argument passed into the parseResponseDom method returns this XML response:

<address>
    <name>Kirk Stevens</name>
    <street1>808 State St</street1>
    <street2>Apt. 2</street2>
    <city>Palookaville</city>
    <state>PA</state>
    <country>USA</country>
</address>

The following example illustrates how to use DOM classes to parse the XML response returned in the body of a GET request:
public class DomDocument {
 
    // Pass in the URL for the request
    // For the purposes of this sample,assume that the URL
    // returns the XML shown above in the response body
    public void parseResponseDom(String url){
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        // url that returns the XML in the response body
        req.setEndpoint(url);
        req.setMethod('GET');
        HttpResponse res = h.send(req);
        Dom.Document doc = res.getBodyDocument();
        
        //Retrieve the root element for this document.
        Dom.XMLNode address = doc.getRootElement();
        //getChildElement() method is present in XML Node Class
        String name = address.getChildElement('name', null).getText();
        String state = address.getChildElement('state', null).getText();
        // print out specific elements
        System.debug('Name: ' + name);
        System.debug('State: ' + state);
        
        // Alternatively, loop through the child elements.
        // This prints out all the elements of the address
        for(Dom.XMLNode child : address.getChildElements()) {
           System.debug(child.getText());
        }
    }
}
XML NameSpaces:
An XML namespace is a collection of names identified by a URI reference and used in XML documents to uniquely identify element types and attribute names. Names in XML namespaces may appear as qualified names, which contain a single colon, separating the name into a namespace prefix and a local part. The prefix, which is mapped to a URI reference, selects a namespace. The combination of the universally managed URI namespace and the document's own namespace produces identifiers that are universally unique.
The following XML element has a namespace of http://my.name.space and a prefix of myprefix.
<sampleElement xmlns:myprefix="http://my.name.space" />
  In the following example, the XML element has two attributes:
  • The first attribute has a key of dimension; the value is 2.
  • The second attribute has a key namespace of http://ns1; the value namespace is http://ns2; the key is foo; the value is bar.
<square dimension="2" ns1:foo="ns2:bar" xmlns:ns1="http://ns1" xmlns:ns2="http://ns2" />

 For more information regarding XML Namespaces Please visit the below link
 http://www.xmlmaster.org/en/article/d01/c10/

XML Node Class in Salesforce



XmlNode Class:

Use the XmlNode class to work with a node in an XML document. The DOM represents an XML document as a hierarchy
of nodes. Some nodes may be branch nodes and have child nodes, while others are leaf nodes with no children.

Node Types:
There are different types of DOM nodes available in Apex. XmlNodeType is an enum of these different types. The values
are:
• COMMENT
• ELEMENT
• TEXT

It is important to distinguish between elements and nodes in an XML document. The following is a simple XML example:

<name>
<firstName>Suvain</firstName>
<lastName>Singh</lastName>
</name>

This example contains three XML elements: name, firstName, and lastName. It contains five nodes: the three name,
firstName, and lastName element nodes, as well as two text nodes—Suvain and Singh. Note that the text within an
element node is considered to be a separate text node.

Methods:

The XmlNode class has the following methods:






XmlNode Example:

This example shows how to use XmlNode methods and namespaces to create an XML request.

public class DomNamespaceSample
{
public void sendRequest(String endpoint)
{
// Create the request envelope
DOM.Document doc = new DOM.Document();
String soapNS = 'http://schemas.xmlsoap.org/soap/envelope/';
String xsi = 'http://www.w3.org/2001/XMLSchema-instance';
String serviceNS = 'http://www.myservice.com/services/MyService/';
dom.XmlNode envelope
= doc.createRootElement('Envelope', soapNS, 'soapenv');
envelope.setNamespace('xsi', xsi);
envelope.setAttributeNS('schemaLocation', soapNS, xsi, null);
dom.XmlNode body
= envelope.addChildElement('Body', soapNS, null);
body.addChildElement('echo', serviceNS, 'req').
addChildElement('category', serviceNS, null).
addTextNode('classifieds');
System.debug(doc.toXmlString());
// Send the request
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setEndpoint(endpoint);
req.setHeader('Content-Type', 'text/xml');
req.setBodyDocument(doc);
Http http = new Http();
HttpResponse res = http.send(req);
System.assertEquals(200, res.getStatusCode());
dom.Document resDoc = res.getBodyDocument();
envelope = resDoc.getRootElement();
String wsa = 'http://schemas.xmlsoap.org/ws/2004/08/addressing';
dom.XmlNode header = envelope.getChildElement('Header', soapNS);
System.assert(header != null);
String messageId= header.getChildElement('MessageID', wsa).getText();
System.debug(messageId); System.debug(resDoc.toXmlString()); System.debug(resDoc); System.debug(header); System.assertEquals( 'http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous', header.getChildElement( 'ReplyTo', wsa).getChildElement('Address', wsa).getText()); System.assertEquals( envelope.getChildElement('Body', soapNS). getChildElement('echo', serviceNS). getChildElement('something', 'http://something.else'). getChildElement( 'whatever', serviceNS).getAttribute('bb', null), 'cc'); System.assertEquals('classifieds', envelope.getChildElement('Body', soapNS). getChildElement('echo', serviceNS). getChildElement('category', serviceNS).getText()); } }

Wednesday, September 18, 2013

XML Stream Classes in Salesforce

Keep watching, as soon as possible I will update this class.....

HttpResponse Class in Salesforce for Handling HTTP Response returned by HTTP Class

Use the HttpResponse class to handle the HTTP response returned by the Http class.

Use the DOM Classes or JSON Classes  to parse XML or JSON content in the body of a response accessed by HttpResponse.


Methods in HTTPResponse Class: 

The HttpResponse class contains the following public methods:
NameArgumentsReturn TypeDescription
getBodyStringRetrieves the body returned in the response. Limit3 MB.
The HTTP request and response sizes count towards the total heap size.
getBodyAsBlobBlobRetrieves the body returned in the response as a Blob. Limit3 MB.
The HTTP request and response sizes count towards the total heap size.
getBodyDocumentDom.DocumentRetrieves the body returned in the response as a DOM document. Use it as a shortcut for:
String xml = httpResponse.getBody();
Dom.Document domDoc = new Dom.Document(xml);
getHeaderString keyStringRetrieves the contents of the response header.
getHeaderKeysString[]Retrieves an array of header keys returned in the response.
getStatusStringRetrieves the status message returned for the response.
getStatusCodeIntegerRetrieves the value of the status code returned in the response.
getXmlStreamReaderXmlStreamReaderReturns an XmlStreamReader (XmlStreamReader Class) that parses the body of the callout response. Use it as a shortcut for:
String xml = httpResponse.getBody();
XmlStreamReader xsr = new XmlStreamReader(xml);
For a full example, see below Example.
setBodyStringVoidSpecifies the body returned in the response.
setBodyAsBlobBlobVoidSpecifies the body returned in the response using a Blob.
setHeaderString key, String valueVoidSpecifies the contents of the response header.
setStatusStringVoidSpecifies the status message returned in the response.
setStatusCodeIntegerVoidSpecifies the value of the status code returned in the response.
toStringStringReturns the status message and status code returned in the response, for example:
Status=OK, StatusCode=200

Example
public class ReaderFromCalloutSample {

  public void getAndParse() {

    // Get the XML document from the external server
    Http http = new Http();
    HttpRequest req = new HttpRequest();
    req.setEndpoint('http://www.cheenath.com/tutorial/sample1/build.xml');
    req.setMethod('GET');
    HttpResponse res = http.send(req);

    // Log the XML content
    System.debug(res.getBody());

    // Generate the HTTP response as an XML stream
    XmlStreamReader reader = res.getXmlStreamReader();

    // Read through the XML
    while(reader.hasNext()) {
      System.debug('Event Type:' + reader.getEventType());
      if (reader.getEventType() == XmlTag.START_ELEMENT) {
        System.debug(reader.getLocalName());
      }
      reader.next();
    }
 
  }
}

In the above getXmlStreamReader example, content is retrieved from an external Web server, then the XML is parsed using the XmlStreamReader class.

Enjoy........Keep Smiling.....

JSON Classes in Salesforce

Site Under maintenance......... Soon I will update the it.

HttpRequest Class in Salesforce for generating HttpRequest

Use the HttpRequest class to programmatically create HTTP requests like GET, POST, PUT, and DELETE.

Use the DOM Classes  or Json Classes to Parse XML or JSON content in the body of a request created by HttpRequest.

Methods:

The HttpRequest class contains the following public methods:

NameArgumentsReturn TypeDescription
getBodyStringRetrieves the body of this request.
getBodyAsBlobBlobRetrieves the body of this request as a Blob.
getBodyDocumentDom.DocumentRetrieves the body of this request as a DOM document. Use it as a shortcut for:
String xml = httpRequest.getBody();
Dom.Document domDoc = new Dom.Document(xml);
getCompressedBooleanIf true, the request body is compressed, false otherwise.
getEndpointStringRetrieves the URL for the endpoint of the external server for this request.
getHeaderString keyStringRetrieves the contents of the request header.
getMethodStringReturns the type of method used by HttpRequest. For example:
  • DELETE
  • GET
  • HEAD
  • POST
  • PUT
  • TRACE
setBodyString bodyVoidSets the contents of the body for this request. Limit: 3 MB.
The HTTP request and response sizes count towards the total heap size.
setBodyAsBlobBlob bodyVoidSets the contents of the body for this request using a Blob. Limit: 3 MB.
The HTTP request and response sizes count towards the total heap size.
setBodyDocumentDom.Document documentVoidSets the contents of the body for this request. The contents represent a DOM document. Limit: 3 MB.
setClientCertificateString clientCert
String password
VoidThis method is deprecated. Use setClientCertificateName instead.
If the server requires a client certificate for authentication, set the client certificate PKCS12 key store and password.
setClientCertificateNameString certDevNameVoidIf the external service requires a client certificate for authentication, set the certificate name. See Using Certificates with HTTP Requests.
setCompressedBoolean flagVoidIf true, the data in the body is delivered to the endpoint in the gzip compressed format. If false, no compression format is used.
setEndpointString endpointVoidSets the URL for the endpoint of the external server for this request.
setHeaderString key
String Value
VoidSets the contents of the request header. Limit 100 KB.
setMethodString methodSets the type of method to be used for the HTTP request. For example:
  • DELETE
  • GET
  • HEAD
  • POST
  • PUT
  • TRACE
You can also use this method to set any required options.
setTimeoutInteger timeoutVoidSets the timeout in milliseconds for the request. This can be any value between 1 and 120,000 milliseconds.
toStringStringReturns a string containing the URL for the endpoint of the external server for this request and the method used, for example, Endpoint=http://YourServer, Method=POST

The following example illustrates how you can use an authorization header with a request, and handle the response:

Example:

public class AuthCallout { public void basicAuthCallout() { HttpRequest req = new HttpRequest(); req.setEndpoint('http://www.yahoo.com'); req.setMethod('GET'); // Specify the required user name and password to access the endpoint // As well as the header and header information String username = 'myname'; String password = 'mypwd'; Blob headerValue = Blob.valueOf(username + ':' + password); String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue); req.setHeader('Authorization', authorizationHeader); // Create a new http object to send the request object // A response object is generated as a result of the request Http http = new Http(); HTTPResponse res = http.send(req); System.debug(res.getBody()); } }

Compression

If you need to compress the data you send, use setCompressed, as the following sample illustrates:
HttpRequest req = new HttpRequest(); req.setEndPoint('my_endpoint'); req.setCompressed(true); req.setBody('some post body');
If a response comes back in compressed format, getBody automatically recognizes the format, uncompresses it, and returns the uncompressed value.