Im trying to use the JSON2Apex to get the parsing class for my API response.. I only need the metrics data for each userId, but I cant get the variable and the system always giving error Variable doesnt exist.. how do I call the variable and get the metrics data of each userId?

public class JSON2Apex {

public class Metrics {
    public String metric {get;set;} 
    public String qualifier {get;set;} 
    public Stats stats {get;set;} 

    public Metrics(JSONParser parser) {
        while (parser.nextToken() != System.JSONToken.END_OBJECT) {
            if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                String text = parser.getText();
                if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                    if (text == 'metric') {
                        metric = parser.getText();
                    } else if (text == 'qualifier') {
                        qualifier = parser.getText();
                    } else if (text == 'stats') {
                        stats = new Stats(parser);
                    } else {
                        System.debug(LoggingLevel.WARN, 'Metrics consuming unrecognized property: '+text);
                        consumeObject(parser);
                    }
                }
            }
        }
    }
}

public List<Results> results {get;set;} 

public JSON2Apex(JSONParser parser) {
    while (parser.nextToken() != System.JSONToken.END_OBJECT) {
        if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
            String text = parser.getText();
            if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                if (text == 'results') {
                    results = arrayOfResults(parser);
                } else {
                    System.debug(LoggingLevel.WARN, 'JSON2Apex consuming unrecognized property: '+text);
                    consumeObject(parser);
                }
            }
        }
    }
}

public class Results {
    public Group_Z group_Z {get;set;} // in json: group
    public List<Data> data {get;set;} 

    public Results(JSONParser parser) {
        while (parser.nextToken() != System.JSONToken.END_OBJECT) {
            if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                String text = parser.getText();
                if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                    if (text == 'group') {
                        group_Z = new Group_Z(parser);
                    } else if (text == 'data') {
                        data = arrayOfData(parser);
                    } else {
                        System.debug(LoggingLevel.WARN, 'Results consuming unrecognized property: '+text);
                        consumeObject(parser);
                    }
                }
            }
        }
    }
}

public class Stats {
    public Integer sum {get;set;} 

    public Stats(JSONParser parser) {
        while (parser.nextToken() != System.JSONToken.END_OBJECT) {
            if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                String text = parser.getText();
                if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                    if (text == 'sum') {
                        sum = parser.getIntegerValue();
                    } else {
                        System.debug(LoggingLevel.WARN, 'Stats consuming unrecognized property: '+text);
                        consumeObject(parser);
                    }
                }
            }
        }
    }
}

public class Data {
    public String interval {get;set;} 
    public List<Metrics> metrics {get;set;} 

    public Data(JSONParser parser) {
        while (parser.nextToken() != System.JSONToken.END_OBJECT) {
            if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                String text = parser.getText();
                if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                    if (text == 'interval') {
                        interval = parser.getText();
                    } else if (text == 'metrics') {
                        metrics = arrayOfMetrics(parser);
                    } else {
                        System.debug(LoggingLevel.WARN, 'Data consuming unrecognized property: '+text);
                        consumeObject(parser);
                    }
                }
            }
        }
    }
}

public class Group_Z {
    public String userId {get;set;} 

    public Group_Z(JSONParser parser) {
        while (parser.nextToken() != System.JSONToken.END_OBJECT) {
            if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                String text = parser.getText();
                if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                    if (text == 'userId') {
                        userId = parser.getText();
                    } else {
                        System.debug(LoggingLevel.WARN, 'Group_Z consuming unrecognized property: '+text);
                        consumeObject(parser);
                    }
                }
            }
        }
    }
}


public static JSON2Apex parse(String json) {
    System.JSONParser parser = System.JSON.createParser(json);
    return new JSON2Apex(parser);
}

public static void consumeObject(System.JSONParser parser) {
    Integer depth = 0;
    do {
        System.JSONToken curr = parser.getCurrentToken();
        if (curr == System.JSONToken.START_OBJECT || 
            curr == System.JSONToken.START_ARRAY) {
            depth++;
        } else if (curr == System.JSONToken.END_OBJECT ||
            curr == System.JSONToken.END_ARRAY) {
            depth--;
        }
    } while (depth > 0 && parser.nextToken() != null);
}




private static List<Metrics> arrayOfMetrics(System.JSONParser p) {
    List<Metrics> res = new List<Metrics>();
    if (p.getCurrentToken() == null) p.nextToken();
    while (p.nextToken() != System.JSONToken.END_ARRAY) {
        res.add(new Metrics(p));
    }
    return res;
}





private static List<Results> arrayOfResults(System.JSONParser p) {
    List<Results> res = new List<Results>();
    if (p.getCurrentToken() == null) p.nextToken();
    while (p.nextToken() != System.JSONToken.END_ARRAY) {
        res.add(new Results(p));
    }
    return res;
}



private static List<Data> arrayOfData(System.JSONParser p) {
    List<Data> res = new List<Data>();
    if (p.getCurrentToken() == null) p.nextToken();
    while (p.nextToken() != System.JSONToken.END_ARRAY) {
        res.add(new Data(p));
    }
    return res;
}
}

This is the API response :

{ "results": [ { "group": { "userId": "4f798b1d-d27a-4415-b793-02b420586e73" }, "data": [ { "interval": "2018-10-01T08:00:00.000Z/2018-10-07T08:00:00.000Z", "metrics": [ { "metric": "tSystemPresence", "qualifier": "AVAILABLE", "stats": { "sum": 270493992 } }, { "metric": "tSystemPresence", "qualifier": "OFFLINE", "stats": { "sum": 247906008 } } ] } ] }, { "group": { "userId": "ab24ddb8-f1ef-4cca-ae72-9f20f5975332" }, "data": [ { "interval": "2018-10-01T08:00:00.000Z/2018-10-07T08:00:00.000Z", "metrics": [ { "metric": "tSystemPresence", "qualifier": "AWAY", "stats": { "sum": 949 } }, { "metric": "tSystemPresence", "qualifier": "MEAL", "stats": { "sum": 2409 } }, { "metric": "tSystemPresence", "qualifier": "MEETING", "stats": { "sum": 31909 } }, { "metric": "tSystemPresence", "qualifier": "AVAILABLE", "stats": { "sum": 204393790 } }, { "metric": "tSystemPresence", "qualifier": "OFFLINE", "stats": { "sum": 313960394 } }, { "metric": "tSystemPresence", "qualifier": "TRAINING", "stats": { "sum": 7885 } }, { "metric": "tSystemPresence", "qualifier": "BUSY", "stats": { "sum": 1839 } }, { "metric": "tSystemPresence", "qualifier": "BREAK", "stats": { "sum": 825 } } ] } ] } ] }

This is what I`ve tried so far

        for (User us : userSF){          
        Purecloud__c ipcccc = new Purecloud__c();
        ipcccc.Name = us.Name+'_'+year+'-'+month+'-'+day;
        ipcccc.Agent__c = '-';
        ipcccc.Agent_Name__c = us.Id;
        ipcccc.Queue_Group__c = 'AFI';
        ipcccc.External_ID__c = us.SIP__c+'_'+year+'-'+month+'-'+day;
        ipcccc.Date__c = date.valueof(startInterval);
        ipcccc.Type__c = 'Daily';
        tempAgent.add(ipcccc);
    }


    String JSONstring = '{  "interval": "'+startInterval+'/'+endInterval+'",  "timeZone": "Asia/Jakarta",  "groupBy": [   "userId"  ],  "filter": {   "type": "or",   "predicates": [';
    String bodypart1 = '{"type":"dimension","dimension":"userId","operator":"matches","value":"';
    String bodypart2 = '"}';
    String endString = ']  },  "metrics": [   "tSystemPresence"  ] }';
    String comma = ',';
    Integer sizeUser = userSF.size();

    for (integer i = 0; i < sizeUser; i++){
        JSONstring += bodypart1 + userSF[i].SIP__c + bodypart2;
        if(i + 1 < sizeUser){
            JSONstring += comma;
        }
    }
    JSONstring += endString;
    System.debug('jsonString = ' + jsonString);


    Http h = new Http();
    HttpRequest req = new HttpRequest();
    req.setEndpoint(url);
    req.setMethod('POST');
    req.setTimeout(120000);
    req.setHeader('content-type', 'application/json');
    req.setHeader('Authorization', 'Bearer '+ token);
    req.setBody(JSONstring);

    try{
        HttpResponse res = new HttpResponse();
        res = h.send(req);
            String parser;
            if (test.isRunningTest()==false) parser = res.getBody();
            system.debug('*body*'+parser);
            JSON2Apex jsonApex = JSON2Apex.parse(parser);
            system.debug('JSON ==>'+jsonApex);

        for (JSON2Apex.results mc : jsonApex.results){
            system.debug('DATA ==>'+ mc.data);
            system.debug('GROUP ==>'+ mc.group_Z);
            string usId = String.valueof(mc.group_Z);
            String trueId = usId.substring(16,51);
            system.debug('usId ==>'+trueId);
        }

I can only get the userId from the results, but not the metrics data (Only need qualifier and sum from each metrics).. I cant get the metrics variable

  • In the future, please refrains from adding 'I am new to...' in your posts, it is irrelevant to the question in hand and of no value. Thanks – glls Oct 21 at 16:57
up vote 2 down vote accepted

If all you want is the user Id, you'll want to edit the file that was returned from JASON2Apex. You need to remove the other objects that aren't being returned in your JSON file. You'll also want to remove the getters and setters for those objects too. Simply editing as below should give you the Groups with the userIds only and should look something more like the following:

public class JSON2Apex2 {

    public class Results {
        public Group_Z group_Z {get;set;} // in json: group

        public Results(JSONParser parser) {
            while (parser.nextToken() != System.JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                        if (text == 'group') {
                            group_Z = new Group_Z(parser);
                        } else if (text == 'data') {
                            data = arrayOfData(parser);
                        } else {
                            System.debug(LoggingLevel.WARN, 'Results consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }

    public List<Results> results {get;set;} 

    public JSON2Apex2(JSONParser parser) {
        while (parser.nextToken() != System.JSONToken.END_OBJECT) {
            if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                String text = parser.getText();
                if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                    if (text == 'results') {
                        results = arrayOfResults(parser);
                    } else {
                        System.debug(LoggingLevel.WARN, 'JSON2Apex2 consuming unrecognized property: '+text);
                        consumeObject(parser);
                    }
                }
            }
        }
    }

    public class Group_Z {
        public String userId {get;set;} 

        public Group_Z(JSONParser parser) {
            while (parser.nextToken() != System.JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                        if (text == 'userId') {
                            userId = parser.getText();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Group_Z consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }


    public static JSON2Apex2 parse(String json) {
        System.JSONParser parser = System.JSON.createParser(json);
        return new JSON2Apex2(parser);
    }

    public static void consumeObject(System.JSONParser parser) {
        Integer depth = 0;
        do {
            System.JSONToken curr = parser.getCurrentToken();
            if (curr == System.JSONToken.START_OBJECT || 
                curr == System.JSONToken.START_ARRAY) {
                depth++;
            } else if (curr == System.JSONToken.END_OBJECT ||
                curr == System.JSONToken.END_ARRAY) {
                depth--;
            }
        } while (depth > 0 && parser.nextToken() != null);
    }



    private static List<Results> arrayOfResults(System.JSONParser p) {
        List<Results> res = new List<Results>();
        if (p.getCurrentToken() == null) p.nextToken();
        while (p.nextToken() != System.JSONToken.END_ARRAY) {
            res.add(new Results(p));
        }
        return res;
    }
}

With additional editing, you'd be able to return a simple list of UserIds but I don't have the time to do that for you at the moment. You'll see that from looking at your source JSON code as illustrated below when you expand it out.

{   "results": [ 
        { 
            "group": { 
                "userId": "4f798b1d-d27a-4415-b793-02b420586e73" 
            },
            "data": [ 
                { 
                    "interval": "2018-10-01T08:00:00.000Z/2018-10-07T08:00:00.000Z", 
                    "metrics": [ 
                        { 
                            "metric": "tSystemPresence", 
                            "qualifier": "AVAILABLE", 
                            "stats": { "sum": 270493992 } 
                        }, 
                        { 
                            "metric": "tSystemPresence", 
                            "qualifier": "OFFLINE", 
                            "stats": { "sum": 247906008 } 
                        } 
                    ] 
                } 
            ] 
        }, 
        { 
        "group": 
            { 
                "userId": "ab24ddb8-f1ef-4cca-ae72-9f20f5975332" 
            }, 
            "data": [ 
                { 
                    "interval": "2018-10-01T08:00:00.000Z/2018-10-07T08:00:00.000Z", 
                    "metrics": [ 
                        { 
                            "metric": "tSystemPresence", 
                            "qualifier": "AWAY", 
                            "stats": { "sum": 949 } 
                        }, 
                        { 
                            "metric": "tSystemPresence", 
                            "qualifier": "MEAL", 
                            "stats": { "sum": 2409 } 
                        }, 
                        {
                            "metric":"tSystemPresence", 
                            "qualifier": "MEETING", 
                            "stats": { "sum": 31909 } 
                        }, 
                        { 
                            "metric": "tSystemPresence", 
                            "qualifier": "AVAILABLE", 
                            "stats": { "sum": 204393790 } 
                        }, 
                        { 
                            "metric": "tSystemPresence", 
                            "qualifier": "OFFLINE", 
                            "stats": { "sum": 313960394 } 
                        },
                        { 
                            "metric": "tSystemPresence", 
                            "qualifier": "TRAINING",
                            "stats": { "sum": 7885 } 
                        }, 
                        { 
                            "metric": "tSystemPresence", 
                            "qualifier": "BUSY",                
                            "stats": { "sum": 1839 } 
                        }, 
                        { 
                            "metric": "tSystemPresence", 
                            "qualifier": "BREAK", 
                            "stats": { "sum": 825 } 
                        } 
                    ] 
                } 
            ] 
        } 
    ] 
}
  • hi @crmprogdev my bad for deleting the post without seeing the notification 1st.. its solved but need some another effort to insert the data to the custom object.. once again sorry my bad, I appreciate your effort! – Arief Gunawan Tjiptorahardja Oct 21 at 14:06

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.