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
Mr WodaMr Woda 

help with this task

 Create inner class with comparator (by lastName asc) for parsing this json:

[{"lastName" : "Perucci", "firstName" : "John", "title" : "guitarist" },{"lastName" : "LaBrie", "firstName" : "James", "title" : "singer"},{"lastName" : "Mabgini", "firstName" : "Mike", "title" : "drummer"},{"lastName" : "Myung", "firstName" : "John", "title" : "basist"}]
Best Answer chosen by Mr Woda
Maharajan CMaharajan C
Hi Andwrii,

Please try the below class:
 
global class JSON2ApexClass implements Comparable  {
    
    global String lastName;
    global String firstName;
    global String title;
    
    
    global static List<JSON2ApexClass> parse(String json) {
        return (List<JSON2ApexClass>) System.JSON.deserialize(json, List<JSON2ApexClass>.class);
    }
    
    global Integer compareTo(Object ObjToCompare) {
        return lastName.CompareTo(((JSON2ApexClass)ObjToCompare).lastName);
    }
}


To Execute: 
 
List<JSON2ApexClass> jsonList = JSON2ApexClass.parse(jsonStr);

jsonList.sort();

System.debug('jsonList --> ' + jsonList );



Thanks,
Maharajan.C

All Answers

SwethaSwetha (Salesforce Developers) 
HI Andrii,
You will need to deserialize JSON with code similar to https://salesforce.stackexchange.com/questions/230777/getting-null-for-inner-classes-in-complex-json-deserialization

https://salesforce.stackexchange.com/questions/223121/how-to-use-json-class-as-a-inner-class-instead-of-seprate-class

Thanks
Maharajan CMaharajan C
Hi Andwrii,

Please try the below class:
 
global class JSON2ApexClass implements Comparable  {
    
    global String lastName;
    global String firstName;
    global String title;
    
    
    global static List<JSON2ApexClass> parse(String json) {
        return (List<JSON2ApexClass>) System.JSON.deserialize(json, List<JSON2ApexClass>.class);
    }
    
    global Integer compareTo(Object ObjToCompare) {
        return lastName.CompareTo(((JSON2ApexClass)ObjToCompare).lastName);
    }
}


To Execute: 
 
List<JSON2ApexClass> jsonList = JSON2ApexClass.parse(jsonStr);

jsonList.sort();

System.debug('jsonList --> ' + jsonList );



Thanks,
Maharajan.C
This was selected as the best answer
Maharajan CMaharajan C
@andrii soloninko ,  If you got the solution... Please close this thread by marking the best answer!!!