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
Yady Kalsi 9Yady Kalsi 9 

Assign JSON value to lookup fields

Hi Guys !!
I am fetching JSON data stream using REST API. I'm filling my custom fields with the JSON data. But I'm stuck in populating lookup field. 
Below is the snippet that does the parsing:

DeviceReading__c obj;
obj = new DeviceReading__c();
while(parser.nextToken() != null) {
       obj.Meter_ID__c = parser.getText(); // Meter_ID__c  is the lookup field of Customer__c object
 }

Please help me 
Raj VakatiRaj Vakati
Hi Yady . 
What is the value at parser.getText() ? I can help you if you can provide the response values at the node.
 obj.Meter_ID__c = parser.getText(); /
 
Yady Kalsi 9Yady Kalsi 9
It is a number, i.e, 16032304. It is same as the other field in Customer__c object.
Raj VakatiRaj Vakati
Hi Yady , 
I believe you should do it with external Id, not with record Id.  use the code here 
 
// I am assuing that you have a custome object records  Customer__c co = new Customer__c(Extenal__c ='16032304');    
// If not create a Customer__c with extenal id 16032304 

DeviceReading__c obj;
obj = new DeviceReading__c();

while(parser.nextToken() != null) {
       obj.Meter_ID__c = parser.getText(); // Meter_ID__c  Should be extenal Id 
 }
 
 

// Create the DeviceReading__c.
Database.SaveResult results = Database.insert(obj;);

 
Raj VakatiRaj Vakati
Refer this link 
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_dml_nested_object.htm
Yady Kalsi 9Yady Kalsi 9
Yes I already have a record with "16032304" in Customer__c object. Should I change data type of Meter_ID__c from lookup to normal text ?
Also for adding I'm using upsert, so do I need to change it:

 while(parser.nextToken() != null) {
             
                if(parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                if(fieldName == 'WaterMeterID') {
                        
                        Customer__c Cobj = new Customer__c(Name = parser.getText());  //Made Change HERE
                        obj.Device_ID__c = Cobj.Name;               //Made Change HERE
                        Istobj.add(obj);
                        count++;
                    }
                }
             upsert Istobj Id;
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, count + ' Records Synced'));
        }
       
So on making the changes as you suggested, I'm getting the following error:

Invalid id: 16032304
Error is in expression '{!syncData}' in component <apex:page> in page testcontroller: Class.TestController.syncData: line 138, column 1
An unexpected error has occurred. Your development organization has been notified.