I am Really Struggling with this code Trying different ways to Convert JSON to HashMap but still no Progress any help regarding the code would be appreciated.I have tried Searching for the problem but it still Gives me other Exceptions like not a JsonObject and already tried a different lib but Google.gson works best for me please let me Know if you have any fix regarding this...
import java.util.HashMap;
import java.net.*;
import java.io.*;
import java.util.Map;
import com.google.gson.*;
import com.google.gson.reflect.*;
public class Weather {
private static Map<String, Object> jsonToMap(String str){
Map<String, Object> map = new Gson().fromJson(
str, new TypeToken<HashMap<String, Object>>() {}.getType()
);
return map;
}
public static void main(String[] args){
String apiKey = "API not Provided";
String urlString = "http://api.openweathermap.org/data/2.5/forecast?id=1174872&APPID=" + apiKey + "&units=metric";
try{
StringBuilder result = new StringBuilder();
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null)
{
result.append(line);
}
reader.close();
System.out.println("json print: ");
System.out.println(result);
Map<String, Object> respMap = jsonToMap(result.toString());
Map<String, Object> mainMap = jsonToMap(respMap.get("main").toString());
Map<String, Object> windMap = jsonToMap(respMap.get("wind").toString());
System.out.println("Current Temperature: " + mainMap.get("temp"));
System.out.println("Current Humidity: " + mainMap.get("humidity"));
System.out.println("Current Wind : " + windMap.get("speed"));
System.out.println("Current Wind Direction : " + windMap.get("deg"));
}catch(NullPointerException e){
System.out.println("Null Pointer Exception Occurred!");
}catch (IOException e)
{
System.out.println("Input Output Exception Occurred!");
}
}
}