+ 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!!!