function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
imrohitimrohit 

How to convert JSON string to Object

[  
   {  
      "Id":"a0F7F000006lv7OUAQ",
      "Name":"Lightning Arrester(ESE Type (50 m -3 Nos , 65m - 3 Nos , 100 m - 6 Nos , 107 m -",
      "Price__c":2998,
      "Stage__c":"Civil Works",
      "Quantity__c":"43"
   },
   {  
      "Id":"a0F7F000006lv7EUAQ",
      "Name":"Safety Lifelines",
      "Price__c":20,
      "Stage__c":"Civil Works",
      "Quantity__c":"45"
   }
]

i have records of custom object with apiname productRenew__c in json string formate and i want to convert this json to corresponding object so that i can save the records to the db

Please Help
Thanks in advance
Best Answer chosen by imrohit
Alain CabonAlain Cabon
Hi,

[ ] = array of objects { } in Json.
String jsonStr = '[{"Id":"0015800001PTKzHAAX","Name":"test1" },{"Id":"0015800001PTKxpAAH","Name":"test2"}]';
    JSONParser parser = JSON.createParser(jsonStr);
    while (parser.nextToken() != null) {
        // Start at the array of accounts.
        if (parser.getCurrentToken() == JSONToken.START_ARRAY) {
            while (parser.nextToken() != null) {
                // Advance to the start object marker to
                //  find next account statement object.
                if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
                    // Read entire account object.
                    Account acc = (Account)parser.readValueAs(Account.class);
                    system.debug('Id:' + acc.Id + ' Name:' + acc.Name);
                }
            }
        }
    }

Just replace: Account with  productRenew__c.
 

All Answers

Alain CabonAlain Cabon
Hi,

[ ] = array of objects { } in Json.
String jsonStr = '[{"Id":"0015800001PTKzHAAX","Name":"test1" },{"Id":"0015800001PTKxpAAH","Name":"test2"}]';
    JSONParser parser = JSON.createParser(jsonStr);
    while (parser.nextToken() != null) {
        // Start at the array of accounts.
        if (parser.getCurrentToken() == JSONToken.START_ARRAY) {
            while (parser.nextToken() != null) {
                // Advance to the start object marker to
                //  find next account statement object.
                if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
                    // Read entire account object.
                    Account acc = (Account)parser.readValueAs(Account.class);
                    system.debug('Id:' + acc.Id + ' Name:' + acc.Name);
                }
            }
        }
    }

Just replace: Account with  productRenew__c.
 
This was selected as the best answer
imrohitimrohit
Thanks Alain Cabon