json parsing data from url getting nullpointException - java

Getting JSONObject from URL-Json source.
public class source02 {
public static void main(String[] args) {
try {
URL url = new URL("http://openapi.seoul.go.kr:8088/sample/json/StationDayTrnsitNmpr/1/5/");
InputStreamReader isr = new InputStreamReader(url.openConnection().getInputStream(), "UTF-8");
JSONObject object = (JSONObject)JSONValue.parse(isr);
JSONObject sdt = (JSONObject) object.get("StationDayTrnsitNmpr");
System.out.println(sdt.get("list_total_count").toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
and Json source
{"StationDayTrnsitNmpr":{"list_total_count":44,"RESULT":{"CODE":"INFO-000","MESSAGE":"정상 처리되었습니다"},"row":[{"SN":"1","STATN_NM":"신도림","WKDAY":333873.0,"SATDAY":298987.0,"SUNDAY":216886.0},{"SN":"2","STATN_NM":"동대문역사문화공원","WKDAY":251049.0,"SATDAY":211456.0,"SUNDAY":150589.0},{"SN":"3","STATN_NM":"충무로","WKDAY":229882.0,"SATDAY":194865.0,"SUNDAY":142150.0},{"SN":"4","STATN_NM":"종로3가","WKDAY":224539.0,"SATDAY":196606.0,"SUNDAY":142525.0},{"SN":"5","STATN_NM":"사당","WKDAY":200985.0,"SATDAY":180230.0,"SUNDAY":134354.0}]}}
getting java.lang.NullPointerException
at api.source02.main(source02.java:16)

Well this is working for me
URL url = new URL("http://openapi.seoul.go.kr:8088/sample/json/StationDayTrnsitNmpr/1/5/");
InputStreamReader isr = new InputStreamReader(url.openConnection().getInputStream(), "UTF-8");
BufferedReader br = new BufferedReader(isr);
StringBuilder response = new StringBuilder();
for (String line = br.readLine(); line != null; line = br.readLine()) {
response.append(line);
}
JSONObject object = new JSONObject(response.toString());
JSONObject sdt = (JSONObject) object.get("StationDayTrnsitNmpr");
System.out.println(sdt.get("list_total_count").toString());

Related

Java - JSONObject Not Found

I am trying to collect a single piece of data from an API, that being the population of a certain country. Everything works properly except for cutting the population value out of the JSON.
{"Info":[{"area":301336,"nativeName":"Italia","capital":"Rome","demonym":"Italian","flag":"https://restcountries.eu/data/ita.svg","alpha2Code":"IT","languages":[{"nativeName":"Italiano","iso639_2":"ita","name":"Italian","iso639_1":"it"}],"borders":["AUT","FRA","SMR","SVN","CHE","VAT"],"subregion":"Southern Europe","callingCodes":["39"],"regionalBlocs":[{"otherNames":[],"acronym":"EU","name":"European Union","otherAcronyms":[]}],"gini":36,"population":60665551,"numericCode":"380","alpha3Code":"ITA","topLevelDomain":[".it"],"timezones":["UTC+01:00"],"cioc":"ITA","translations":{"br":"Itália","de":"Italien","pt":"Itália","ja":"イタリア","hr":"Italija","it":"Italia","fa":"ایتالیا","fr":"Italie","es":"Italia","nl":"Italië"},"name":"Italy","altSpellings":["IT","Italian Republic","Repubblica italiana"],"region":"Europe","latlng":[42.83333333,12.83333333],"currencies":[{"symbol":"\u20ac","code":"EUR","name":"Euro"}]}]}
Within the JSON, It is called "Population".
This is my user input code
public static String UserInputsDetails() {
System.out.println("Please input the country name");
Scanner in = new Scanner(System.in);
String Input = in.nextLine();
return Input;
}
This is my JSON Getter Code
public static JSONArray MakeConnection(String countryname) {
JSONArray JSON = null;
try {
String url = "https://restcountries.eu/rest/v2/name/" + countryname;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSON = new JSONArray(response.toString());
} catch (Exception e) {
System.out.println(e);
}
return JSON;
}
This is my Result code, to get just the population
public static void PrintResult(JSONArray JSON){
String population = null;
try {
JSONObject jobj = new JSONObject();
jobj.put("Info", JSON);
population = jobj.getString("population");
System.out.println(jobj);
System.out.println(population);
} catch (Exception e) {
System.out.println(e);
}
}
And finally, this is my main
public static void main(String []args) {
String Input = UserInput.UserInputsDetails();
JSONArray JSON = Connection.MakeConnection(Input);
Result.PrintResult(JSON);
}
I get the error
org.json.JSONException: JSONObject["population"] not found.
What am I doing wrong?
Delete this part:
JSONObject jobj = new JSONObject();
jobj.put("Info", JSON);
population = jobj.getString("population");
System.out.println(jobj);
System.out.println(population);
JSON is already an array, why are you converting it into a JSONObject?
Change to something like this:
Long population = JSON.getJSONObject(0).getLong("population");

Java: Can't send HTTP Post Request in Catch

I need to post request to an API inside catch to store some logs.
But when I put it the request inside catch, it returned:
java.io.IOException: Server returned HTTP response code: 500 for URL
Code:
try {
...
} catch (Exception e) {
postRequest(...);
}
Code Post Request to API;
public static Object postRequest(...) throws IOException, ParseException {
URL url = new URL(API + "/" + pathName);
HttpURLConnection connection = getHttpURLConnection(url);
try (OutputStream os = connection.getOutputStream()) {
byte[] input = body.getBytes("utf-8");
os.write(input, 0, input.length);
}
try {
StringBuilder response = new StringBuilder();
InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream(), "utf-8");
BufferedReader br = new BufferedReader(inputStreamReader);
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject) parser.parse(response.toString());
return obj;
} catch (IOException err) {
return null;
}
}

Android not able to recognize different language Fonts

Made an app to translate different words to different Language
Using Yandex converter getting proper results on Browser
converting Kiss
RESULTS as JSON object is
{"code":200,"lang":"en-hi","text":["चुम्बन"]} //proper
but while getting result on app
RESULT
{"code":200,"lang":"en-hi","text":["à¤à¥à¤®à¥à¤¬à¤¨"]}
JSONParser jParser = new JSONParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
geJSONFromUrl function
public JSONObject getJSONFromUrl(String urlSource) {
//make HTTP request
try {
URL url = new URL(urlSource);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
inputStream = new BufferedInputStream(urlConnection.getInputStream());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Read JSON data from inputStream
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
json = sb.toString();
} catch (Exception e) {
Log.e(TAG, "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e(TAG, "Error parsing data " + e.toString());
}
return jObj;// return JSON String
}
}
Is there any way i can get proper results?
Please HelpRegards
changed
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
to
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);

parse JSON format using GSON?

With HTTPURLCONNECTION I am able to get the JSON response and using Writer I am able to save it to output.json file also. But I am not able to read the content of output.json or directly from the url "http://somesite.com/json/server.json" using GSON. I am facing few issues when using gson.
public class ConnectToUrlUsingBasicAuthentication {
public static void main(String[] args) {
try {
String webPage = "http://somesite.com/json/server.json";
//HTTPURLCONNECTION
URL url = new URL(webPage);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
StringBuilder sb = new StringBuilder();
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is,Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(isr);
String line;
while((line = bufferedReader.readLine()) != null) {
System.out.println("*** BEGIN ***");
try(Writer writer = new OutputStreamWriter(new FileOutputStream("Output.json") , "UTF-8")){
Gson gson = new GsonBuilder().create();
gson.toJson(line, writer);
System.out.println("Written successfully");
}
System.out.println(line);
System.out.println("*** END ***");
try(Reader reader = new InputStreamReader(is, "UTF-8")){
Gson gson = new GsonBuilder().create();
JsonData p = gson.fromJson(reader, JsonData.class);
System.out.println(p);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The other class I am passing during gson.fromjson call is Jsondata.
public class JsonData {
private String body;
private List<String> items = new ArrayList<String>();
private List<String> messages = new ArrayList<String>();
// Getters and setters are not required for this example.
// GSON sets the fields directly using reflection.
#Override
public String toString() {
return messages + " - " + items + " - " + messages ;
}
}
Outputs:
Json format (Is the JSON format looks fine or any syntax error is there in it)
line = {
"body":
{"items":[
{"name":"server","state":"RUNNING","health":"HEALTH_OK"},
{"name":"server1","state":"RUNNING","health":"HEALTH_OK"},
{"name":"server2","state":"RUNNING","health":"HEALTH_OK"}
]},
"messages":[]}
Value printed for variable p is null.
Could some one please help me in printing the Json response in variable p using Gson.
Wait until you've read the entire response body before you try and convert it with GSON.
try (Writer writer = new OutputStreamWriter(
new FileOutputStream("Output.json") , "UTF-8")) {
Gson gson = new GsonBuilder().create();
while((line = bufferedReader.readLine()) != null) {
gson.toJson(line, writer);
}
}
// Now read it.
try (Reader reader = new InputStreamReader(is, "UTF-8")){
Gson gson = new GsonBuilder().create();
JsonData p = gson.fromJson(reader, JsonData.class);
System.out.println(p);
}

How to parse all JSON values correctly in Android

First the: Android Code
public class MachineController extends AsyncTask<String, String,List<Machine>> {
private static String REST_URL = "...";
List<Machine> machines;
#Override
protected List<Machine> doInBackground(String... params) {
machines = new ArrayList<Machine>();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(REST_URL);
httpGet.addHeader("accept", "application/json");
HttpResponse response;
try {
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "n");
String result = sb.toString();
Gson gson = new Gson();
JsonReader jsonReader = new JsonReader(new StringReader(result));
jsonReader.setLenient(true);
JsonParser parser = new JsonParser();
JsonArray jsonArray = parser.parse(jsonReader).getAsJsonArray();
for (JsonElement obj : jsonArray) {
Machine machine = gson.fromJson(obj.getAsJsonObject().get("mobileMachine"), Machine.class);
machines.add(machine);
machines.get(0);
}
instream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return machines;
}
}
Here is some Code of the JSON File
[
{ "mobileMachine":
{ "condition":"VERY_GOOD",
"document":"", . . .
"mobileCategory": { "idNr":"1816e5697eb3e0c8442786be5274cb05cff04c06b4338467c8679770bff32313f7f372b5ec2f7527dad0de47d0fb117e",
"mobileCategoryEng":"Bookletmaker",
"mobileCategoryGer":"Broschuerenfertigung" },
"modelYear":2006,
Abmessungen: 665x810mm " } }
{ "mobileMachine":
{
"condition":"VERY_GOOD"," ...... } } ]
Sometimes there is a mobileCategory inside. The mobileCategoryGer and mobileCategoryEng are allways null in the List.
I can't edit the JSON File! I only want the value for mobileCategoryGer and mobileCategoryEng from the Json File. The Rest works fine. I hope u understand and can help me to parse it correctly.
(Sorry for my english)
Here you go.
Type listType = new TypeToken<List<Machine>>() {}.getType();
ArrayList<Result> results = gson.fromJson(result, listType);
Here is your complete modified code:
public class MachineController extends AsyncTask<String, String,List<Machine>> {
private static String REST_URL = "...";
List<Machine> machines;
#Override
protected List<Machine> doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(REST_URL);
httpGet.addHeader("accept", "application/json");
HttpResponse response;
try {
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "n");
String result = sb.toString();
Gson gson = new Gson();
Type listType = new TypeToken<List<Machine>>() {}.getType();
machines= gson.fromJson(result, listType);
instream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return machines;
}
You could check if it has the key with has() method. Also you can get optional value with optJSONObject() and check if it is not null.
JsonArray jsonArray = parser.parse(jsonReader).getAsJsonArray();
try {
doSomething(jsonArray);
} catch (JSONException e) {
Log.wtf("Terrible Failure", e);
}
private void doSomething(JsonArray jsonArray) throws JSONException{
for (int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
JSONObject mobileCategory = obj.optJSONObject("mobileCategory");
if(mobileCategory !=null){
if(mobileCategory.has("mobileCategoryEng") && mobileCategory.has("mobileCategoryGer") ){
String mobileCategoryEng = mobileCategory.getString("mobileCategoryEng");
String mobileCategoryGer = mobileCategory.getString("mobileCategoryGer");
}
}
}
}

Categories

Resources