0

I'm calling one rest API and it's working properly but I'm not able to deserialize it's reesult.

Below in mentioned my code and what response in I'm getting,I want city value in city variable and temp,humidity in each separate variable's:

public class getCityWeather 
{
    public string city{get;set;}
    public string temp{get;set;}
    public string pressure{get;set;}
    public string humidity{get;set;}
    public string temp_min{get;set;}
    public string temp_max{get;set;}

    public static void CallingOpenWeatherMap()
    {
        String accountCity = 'Delhi';
        String apiKey = 'd0b522134dc8a5ba20020e0bfbceaafa';

        String requestEndPoint = 'http://api.openweathermap.org/data/2.5/weather';
        requestEndPoint+='?q='+accountCity;
        requestEndPoint+='&units=metric';
        requestEndPoint+='&APPID='+apiKey;

        Http http= new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint(requestEndPoint);
        request.setMethod('GET');
        HttpResponse response = http.send(request);

        if(response.getStatusCode() == 200)
        {
            System.debug('Result : '+response.getBody());
        }
    }
}

// And the response is :

{
"coord":{"lon":77.22,"lat":28.65},
"weather":[{"id":721,"main":"Haze","description":"haze","icon":"50d"}],
"base":"stations",
"main":{"temp":34,"pressure":1006,"humidity":52,"temp_min":34,"temp_max":34},
"visibility":3500,
"wind":{"speed":5.1,"deg":320},
"clouds":{"all":20},
"dt":1537342200,
"sys":{"type":1,"id":7809,"message":0.0045,"country":"IN","sunrise":1537317481,"sunset":1537361480},
"id":1273294,
"name":"Delhi",
"cod":200
}
1
2

By means of JSON2Apex application, I got the following class:

public class JSON2Apex {

    public class Weather {
        public Integer id {get;set;} 
        public String main {get;set;} 
        public String description {get;set;} 
        public String icon {get;set;} 

        public Weather(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 == 'id') {
                            id = parser.getIntegerValue();
                        } else if (text == 'main') {
                            main = parser.getText();
                        } else if (text == 'description') {
                            description = parser.getText();
                        } else if (text == 'icon') {
                            icon = parser.getText();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Weather consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }

    public class Coord {
        public Double lon {get;set;} 
        public Double lat {get;set;} 

        public Coord(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 == 'lon') {
                            lon = parser.getDoubleValue();
                        } else if (text == 'lat') {
                            lat = parser.getDoubleValue();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Coord consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }

    public class Wind {
        public Double speed {get;set;} 
        public Integer deg {get;set;} 

        public Wind(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 == 'speed') {
                            speed = parser.getDoubleValue();
                        } else if (text == 'deg') {
                            deg = parser.getIntegerValue();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Wind consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }

    public Coord coord {get;set;} 
    public List<Weather> weather {get;set;} 
    public String base {get;set;} 
    public Main main {get;set;} 
    public Integer visibility {get;set;} 
    public Wind wind {get;set;} 
    public Clouds clouds {get;set;} 
    public Integer dt {get;set;} 
    public Sys sys {get;set;} 
    public Integer id {get;set;} 
    public String name {get;set;} 
    public Integer cod {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 == 'coord') {
                        coord = new Coord(parser);
                    } else if (text == 'weather') {
                        weather = arrayOfWeather(parser);
                    } else if (text == 'base') {
                        base = parser.getText();
                    } else if (text == 'main') {
                        main = new Main(parser);
                    } else if (text == 'visibility') {
                        visibility = parser.getIntegerValue();
                    } else if (text == 'wind') {
                        wind = new Wind(parser);
                    } else if (text == 'clouds') {
                        clouds = new Clouds(parser);
                    } else if (text == 'dt') {
                        dt = parser.getIntegerValue();
                    } else if (text == 'sys') {
                        sys = new Sys(parser);
                    } else if (text == 'id') {
                        id = parser.getIntegerValue();
                    } else if (text == 'name') {
                        name = parser.getText();
                    } else if (text == 'cod') {
                        cod = parser.getIntegerValue();
                    } else {
                        System.debug(LoggingLevel.WARN, 'JSON2Apex consuming unrecognized property: '+text);
                        consumeObject(parser);
                    }
                }
            }
        }
    }

    public class Clouds {
        public Integer all {get;set;} 

        public Clouds(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 == 'all') {
                            all = parser.getIntegerValue();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Clouds consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }

    public class Sys {
        public Integer type_Z {get;set;} // in json: type
        public Integer id {get;set;} 
        public Double message {get;set;} 
        public String country {get;set;} 
        public Integer sunrise {get;set;} 
        public Integer sunset {get;set;} 

        public Sys(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 == 'type') {
                            type_Z = parser.getIntegerValue();
                        } else if (text == 'id') {
                            id = parser.getIntegerValue();
                        } else if (text == 'message') {
                            message = parser.getDoubleValue();
                        } else if (text == 'country') {
                            country = parser.getText();
                        } else if (text == 'sunrise') {
                            sunrise = parser.getIntegerValue();
                        } else if (text == 'sunset') {
                            sunset = parser.getIntegerValue();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Sys consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }

    public class Main {
        public Integer temp {get;set;} 
        public Integer pressure {get;set;} 
        public Integer humidity {get;set;} 
        public Integer temp_min {get;set;} 
        public Integer temp_max {get;set;} 

        public Main(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 == 'temp') {
                            temp = parser.getIntegerValue();
                        } else if (text == 'pressure') {
                            pressure = parser.getIntegerValue();
                        } else if (text == 'humidity') {
                            humidity = parser.getIntegerValue();
                        } else if (text == 'temp_min') {
                            temp_min = parser.getIntegerValue();
                        } else if (text == 'temp_max') {
                            temp_max = parser.getIntegerValue();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Main 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<Weather> arrayOfWeather(System.JSONParser p) {
        List<Weather> res = new List<Weather>();
        if (p.getCurrentToken() == null) p.nextToken();
        while (p.nextToken() != System.JSONToken.END_ARRAY) {
            res.add(new Weather(p));
        }
        return res;
    }
}

you can parse your JSON string in the following way:

JSON2Apex parsedResult = JSON2Apex.parse(responseBody);

interesting, that fields of JSON response has naming conflicts with apex, so that commentary to auto-generated class is added

// The supplied json has fields with names that are not valid in apex

// and so can only be parsed with explicitly generated code, this option

// was auto selected for you.

0

Just create wrapper class for your JSON and simply deserialize it as below

public class WeatherResp{

public Map<String, decimal> coord{get;set;}
public List<Map<String, String>> weather{get;set;}
public String stations {get;set;}
public Map<String, long> main{get;set;}
public Long visibility {get;set;}
public Map<String, decimal> wind{get;set;}
public Map<String, Integer> clouds{get;set;}
public Long dt {get;set;}
public Map<String, String> sys{get;set;}
public Long wid {get;set;}
public String wname {get;set;}
public Integer cod {get;set;}

}

String strJSONResp = response.getBody();
strJSONResp = strJSONResp.replace('"id":', '"wid":');
strJSONResp = strJSONResp.replace('"name":', '"wname":');

WeatherResp objWeatherResp = (WeatherResp) JSON.deserialize(strJSONResp, WeatherResp.class);
2
  • Thanks Sunil for your response, It's giving me error : System.JSONException: Apex Type unsupported in JSON: Object Sep 19 '18 at 10:02
  • Hi Ranjeet, I have update code replace object by string pls check Sep 19 '18 at 10:12

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