Salesforce 0 Basic Development Primer Learn (13) use of JSON in Salesforce

Source: Internet
Author: User

JSON is a popular lightweight data interchange format, and Salesforce also has a good class to encapsulate it. When you interact back and forth in Salesforce, you use JSON to serialize and deserialize the Apex object object.

There are three main classes of processing Json:1.system.json;2.system.jsongenerator;3.system.jsonparser

These methods throw a Jsonexception exception if the call occurs with an error.

A) System.json

Use JSON classes and methods to perform round-trip serialization and deserialization of JSON content, which allows you to serialize object objects into JSON content, and also allow the JSON content to be deserialized into object objects;

The main methods are as follows:

1.public static String Serialize (object Objecttoserialize): This method is used to serialize object objects into JSON content.

2.public static String Serializepretty (object objecttoserialize: This method is used to serialize object objects into JSON content, and the difference between the methods above is only output in a beautifully formatted output format for this method.

Here's an example:

list<goods__c> Goods = [select Id,name,goodsname__c from Goods__c limit 1];
//Serialized by Serialize Method String Goodstojson = json.serialize (goods);
Serialization of String goodstojsonpretty = Json.serializepretty (Goods) by the Serializepretty method; System.debug (Goodstojson); System.debug (Goodstojsonpretty);

The output results are as follows:

[{"Attributes": {"type": "Goods__c", "url": "/services/data/v36.0/sobjects/goods__c/a002800000vgxdqaad"}, "Id": " A002800000vgxdqaad "," Name ":" A002800000VGXDQ ",
"Goodsname__c": "Phantom Blue Note3"}][{" attributes": { "type": "Goods__c", "url": "/services/data/v36.0/ Sobjects/goods__c/a002800000vgxdqaad " }, " Id ":" A002800000vgxdqaad ", " Name ":" A002800000VGXDQ ", "Goodsname__c": "The Charm of Blue Note3"}]

3.public static Object Deserialize (String jsonstring, System.Type apextype): This method is used to deserialize the JSON content into an Apex object object

Serialize samplelist<goods__c> goodslist = (list<goods__c>) json.deserialize (goodstojson,list< Goods__c>.class); for (Goods__c goodsitem:goodslist) {if (Goodsitem.goodsname__c! = null) {System.debug ( Goodsitem.goodsname__c);}}

4.public static Object deserializeuntyped (String jsonstring): This method is used to deserialize the specified JSON content into a collection of base data types, if not the base data type. Then in the deserialization times exception: System.TypeException:Invalid conversion from runtime type list<any> to List<xxx>. eg

String jsonlist = ' [{' 2 ': ' Object2 ', ' 1 ': ' Object1 '}] '; List<object> Listjson = (list<object>) json.deserializeuntyped (jsonlist); for (Object Listitem:listjson) {   if (listItem instanceof map<string,object>) {   system.debug (' deserialization via JSON (MAP) ' + (map<string,object >) listItem);   } else {   system.debug (' Deserialization through JSON ' + ListItem ');}   }

Note: The Sobject type cannot be deserialized by the Deserializeuntyped method, only the base data type is allowed to deserialize.

5.public static System.jsongenerator CreateGenerator (Boolean prettyprint): Returns the Jsongenerator object, Where the formal parameter prettyprint represents jsongenerator to create the JSON content to follow the indentation format, set to True to follow.

6.public static System.jsonparser Createparser (String jsonstring): Returns the Jsonparser object, where the formal parameter jsonstring represents the contents of the JSON to parse.

II) jsongenerator

This class contains methods that are used to serialize object objects into JSON content through standard JSON encoding, which is primarily intended to write values of various types to the JSON contents (equivalent to instantiating JSON content value). The method is as follows:

1.public void Close (): The content cannot be written again after the JSON generator is closed.

2.public Boolean isClosed (): Determines whether the JSON generator is turned off, or returns False if off returns true.

3.public String getasstring (): Returns the contents of the generated JSON;

4.public Void Writeboolean (Boolean Blobvalue): Writes the specified boolean type value;

5.public void WriteXXX: See API for details

Jsongenerator Jsongenerator = Json.creategenerator (True); Jsongenerator.writestartarray (); Jsongenerator.writestartobject (); Jsongenerator.writebooleanfield (' Isstatus ', true); Jsongenerator.writeendobject ();    Jsongenerator.writeendarray (); Jsongenerator.close (); System.debug (Jsongenerator.getasstring ());

Operation Result:

[{  "Isstatus": true}]

III) Jsonparser

Use the System.jsonparser class to parse a returned response content that invokes the JSON format of an external service, such as the JSON format of the Web service callout. The main methods are as follows:

1.public Void Clearcurrenttoken (): This method is used to clear the current token. After this method executes, the Hascurrenttoken method returns False,getcurrenttoken returns NULL, and the Getlastclearedtoken method is called to restore the token;

2.public System.jsontoken Getcurrenttoken (): Gets the current token;

//Advance to the next token. while (parser.nexttoken () = null) {     system.debug (' Current token: ' + Parser.getcurrenttoken ())}

3.public boolean getbooleanvalue (); Gets the boolean value;

4.public Boolean GetXXX (): See the API documentation for details;

 1  String jsoncontent = ' {"isActive": true} '  ; 2  jsonparser parser = Json.createparser ( Jsoncontent);   3  //  4  parser.nexttoken ();  5   Advance to the next value.  6  parser.nextvalue ();  7   Get The Boolean value.  8  Boolean isActive = Parser.getbooleanvalue (); 

5.public System.jsontoken NextToken (): Returns the next token, or null if it has reached the end of the input stream;

IV) Jsontoken Enum

This enumeration class defines some token values that are used to parse JSON content.

Summary: If you use JSON serialization and deserialization normally, the serialize and deserialize methods in the System.json class are sufficient. If you need to customize the JSON style, you can use the Json.generate class to customize the JSON content (rarely encountered in the project, usually two of the JSON classes are done).

This is just a partial list of methods, please check the API yourself. If there is a wrong place to welcome criticism, if there are questions welcome to discuss the message, reproduced please indicate the source.

Salesforce 0 Basic Development Primer Learn (13) use of JSON in Salesforce

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.