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
Jonathan SheehanJonathan Sheehan 

Problem iterating over a JSON object

I have a class that converts a JSON object (stored in a field) into an APEX List.  Once I convert it, I am having a hard time getting the data out of the APEX List.  Can someone please point me in the right direction?

My class is here:
public class JSON2Apex {

    public List<LineItems> lineItems;

    public class LineItems {
        public Double UnitPrice;
        public Double Quantity;
        public String ProductName;
    }

    
    public static JSON2Apex parse(String json) {
        return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class);
    }
    
    }

And my Trigger is here:
trigger parseJSON on COrders__c (after insert) {

          List<COrder_Item__c> itemsToAdd = new List<COrder_Item__c>();
    
            for (COrders__c c: Trigger.new) {
                     if(c.TempJSONOrderInfo__c != null) {
                        JSON2Apex JSONL = JSON2Apex.parse(c.TempJSONOrderInfo__c);
    
                        for(List < LineItems > l:  JSONL){
                        COrder_Item__c i = new COrder_Item__c(COrder__c=c.Id, Price__c=l.UnitPrice, Product__c=l.ProductName, Quantity__c=l.Quantity);
                        itemsToAdd.add(i);
                        } 
                                       
                    }
                   
            }
    database.insert (itemsToAdd, false);
    
}

Sample JSON Data is:
{"lineItems":[{"UnitPrice":139.99,"Quantity":5.0,"ProductName":"Leader"},{"UnitPrice":139,"Quantity":1.0,"ProductName":"Student"}]}

 
Amit Chaudhary 8Amit Chaudhary 8
Hi Jonathan Sheehan,

As per your JSON data you are getting array of "LineItams". So you need to use only below class
 
{"lineItems":[{"UnitPrice":139.99,"Quantity":5.0,"ProductName":"Leader"},{"UnitPrice":139,"Quantity":1.0,"ProductName":"Student"}]}

Apex class
 
public class JsonParser{
		public list<lineItems> lineItems{get;set;}
	public class lineItems{
		public String ProductName{get;set;}
		public Decimal Quantity{get;set;}
		public Decimal UnitPrice{get;set;}
	}
}

I hope your above code is working fine? Please let us know if you need any other help.