1

I have a question on how can I store the JSON Returned Response (name, email) wherein I currently store all of it in a field in a form of JSON and store it on a custom object on a specific field like for example is EMAIL and name field? Meaning Parsing it first and store it on field.

5

If you've JSON format something like below:

{
  "Name":"",
  "AccountNumber":"1312321"
}

then you can try like this:

String jsonString = '{"Name":"ABC","AccountNumber":"1312321"}';
Account act = (Account) JSON.deserialize(jsonString, Account.class);
System.debug('Account:'+act.Name);

It works because JSON object's each field label matches with Account object.

Similarly if you've list of Accounts in your JSON then try like this:

[
  {
    "Name":"ABC",
    "AccountNumber":"1312321"
  },
  {
    "Name":"DEF",
    "AccountNumber":"456456"
  }
]

Apex code for list of Accounts:

String jsonString = '[{"Name":"ABC","AccountNumber":"1312321"},{"Name":"DEF","AccountNumber":"456456"}]';
List<Account> actList = (List<Account>) JSON.deserialize(jsonString, List<Account>.class);
System.debug('Count:'+actList.size());

And finally if your mappings don't map with any of Standard/Custom Object, then you can create a Apex class with those JSON labels and parse your JSON to that ApexType. For Example:

JSON String:

{
  "price":100,
  "startDate":"09-09-2009",
  "endDate":"09-10-2009",
  "name":"IPHONE",
  "category":"Mobile"

}

Apex Class:

public class CustomClass {
    public Integer price;
    public date startDate;
    public date endDate;
    public String name;
    public String category;
}

Deserialize JSON:

String jsonString = '{"price":100,"startDate":"09-09-2009","endDate":"09-10-2009","name":"IPHONE","category":"Mobile"}';
CustomClass obj = (CustomClass) JSON.deserialize(jsonString, CustomClass.class);
System.debug('CustomClass:'+obj.name);
  • but how do i store those json that been deserialize in a field in a custom objects – Torrific Oct 14 '17 at 17:45
  • Retrieve that custom object record and use JSON.serialize() method. It will return a String containing JSON format of that record. Refer this documentation. – Rohit Mourya Oct 14 '17 at 18:12
  • You can't store deserialized objects in a field. But you can use a lookup field between these objects. childObject.LookupToDeserializedObject__c = JSON.deserialize(json, ParentObject__c.SObjectType); – Basti Oct 15 '17 at 14:01
  • it always have this error Unexpected character ('p' (code 112)): was expecting comma to separate OBJECT entries at [line:1, column:170] – Torrific Oct 16 '17 at 14:03
  • @Torrific post your code, it's hard to tell without looking at your code. – Rohit Mourya Oct 17 '17 at 4:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.