So I am trying to retrieve JSON object from url.
And I cannot retrieve anything from url.
So to test why, I tried the same code on Spring application, and it works just fine.
It crashes on code below only on android environment.
Please help
package com.example.sandbox;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
}
Please check your internet connection and also check if you have added permission for INTERNET in your app's manifest that might be issue.
what error do you get exactly ?
Related
I would like to process JSON data started with an object that I don't need.
Here you have the URL:
http://datos.santander.es/api/rest/datasets/callejero_calles.json?items=819
I have been trying to adapt next code, but I don't know how to avoid the first object (summary) and take the second one (resources).
If I want to take one by one all the data inside from each object of "resources" (for example, showing "nombre-calle", "tipo-via"...).
package leerjson;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class LeerJSON {
public static void main(String[] args) throws ParseException {
JSONParser parser = new JSONParser();
try {
URL oracle = new URL("http://datos.santander.es/api/rest/datasets/callejero_calles.json?items=819"); // URL to Parse
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
in.readLine();
while ((inputLine = in.readLine()) != null) {
JSONArray a = (JSONArray) parser.parse(inputLine);
// Loop through each item
for (Object o : a) {
JSONObject datos = (JSONObject) o;
System.out.println(datos);
}
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
UPDATED:
Once seen Enra64's answer, I don't know how to use getJSONArray and getJSONObject because it is not a method. I have included json-simple-1.1.1.jar to my project, but it doesn't work. Thank you in advance! This is my new code:
URL oracle = new URL("http://datos.santander.es/api/rest/datasets/callejero_calles.json?items=819"); // URL to Parse
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine = in.readLine();
JSONObject a = (JSONObject) parser.parse(inputLine);
JSONArray resources = a.getJSONArray("resources");
for (int i = 0; i < resources.length(); i++) {
resources.getJSONObject(i);
}
Select the resources object as follows:
JSONObject a = (JSONObject) parser.parse(inputLine);
JSONArray resources = a.getJSONArray("resources");
And then loop through it:
for (int i = 0; i < resources.length(); i++) {
resources.getJSONObject(i);
}
How can I "put" the output generated, which looks to be valid JSON, into an actual JSON object?
According to this answer, gson requires that a class be defined. Surely there's a dynamic way to load or define a class? Or a generic type?
In XML a schema or DTD would be available. Can I dynamically load or find something like that for JSON, using gson?
code:
package net.bounceme.noagenda;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import static java.lang.System.out;
public class NoAgenda {
public static void main(String[] args) throws MalformedURLException, IOException {
List<URL> urls = new ArrayList<>();
new NoAgenda().iterateURLs(urls);
}
private void iterateURLs(List<URL> urls) throws MalformedURLException, IOException {
urls.add(new URL("https://www.flickr.com/photos/"));
urls.add(new URL("http://www.javascriptkit.com/dhtmltutors/javascriptkit.json"));
urls.add(new URL("http://api.wunderground.com/api/54f05b23fd8fd4b0/geolookup/conditions/forecast/q/US/CO/Denver.json"));
for (URL url : urls) {
connect(url);
}
}
private void connect(URL url) throws IOException {
out.println(url);
String line = null;
StringBuilder sb = new StringBuilder();
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
while ((line = in.readLine()) != null) {
sb.append(line + "\n");
}
in.close();
out.println(sb);
// HOW DO I TURN THIS INTO AN ACTUAL JSON??
}
}
wikipedia says:
Schema and metadata
JSON Schema
JSON Schema[20] specifies a JSON-based format to define the structure
of JSON data for validation, documentation, and interaction control. A
JSON Schema provides a contract for the JSON data required by a given
application, and how that data can be modified.
The arbitrary three URL's I'm working with:
https://www.flickr.com/photos/
http://www.javascriptkit.com/dhtmltutors/javascriptkit.json
http://api.wunderground.com/api/54f05b23fd8fd4b0/geolookup/conditions/forecast/q/US/CO/Denver.json
You can use following
StringBuilder sb = new StringBuilder();
String line;
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
JSONObject json = new JSONObject(sb.toString());
Am working on J2ee web application and am trying to get the code JSON of a web page via it's url in purpose to parse it later. I've already tried the code below:
package so4308554;
import java.io.BufferedReader;
import java.io.IOException;``
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import org.json.JSONException;
import org.json.JSONObject;
public class JsonReader {
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
JSONObject json = readJsonFromUrl("https://graph.facebook.com/19292868552");
System.out.println(json.toString());
System.out.println(json.get("id"));
}
}
But it works only with the given url if i put another one i get this exception:
"A JSONObject text must begin with '{' at character 1"
I think i can't get the Json content of web page if it is coded by html... any idea of what could be the causes??????? And how can i resolve my problem???
Are you trying to get json out of an html web page?
If the answer to the previous question is "No", validate the json you're trying to parse with something like this: http://jsonlint.com/, and check out the results.
I'm trying to do a project in Android where I have a document xml from a web and i want to convert in Json.
I'm trying this:
URL url;
InputStream in;
try {
url = new URL("http://www.aemet.es/xml/municipios/localidad_41091.xml");
in = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String result, line = reader.readLine();
result = line;
while((line=reader.readLine())!=null){
result+=line;
}
XMLSerializer serializer = new XMLSerializer();
JSON json = serializer.read( result );
System.out.println(json.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
but does not work ... can someone help me
Send the entire xml document as string instead of reading line by line
import java.io.InputStream;
import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;
import org.apache.commons.io.IOUtils;
public class ConvertXMLtoJSON {
public static void main(String[] args) throws Exception {
InputStream is =
ConvertXMLtoJSON.class.getResourceAsStream("sample-xml.xml");
String xml = IOUtils.toString(is);
XMLSerializer xmlSerializer = new XMLSerializer();
JSON json = xmlSerializer.read( xml );
System.out.println( json.toString(2) );
}
}
If you want generic conversion you can use org.json
I'm using the following class to read a JSON file on some URL and make a JSONObject from it. When outputting something on the screen the program gets terminated without anything in the console. This is the code:
public class JsonReader {
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
System.out.println("in main!");
JSONObject json = readJsonFromUrl("http://somesubdomain.domain.com/blabla.json");
//System.out.println(json.get("id"));
}
}
It's really weird because it seems it doesn't even go in the main method. I just validated the JSON file and there's nothing wrong with it. Anybody any idea? Thanks.
EDIT: I found out that this works in a project on its own. This happens only when in the main package of the Android project.
Is this an android project? There is no public static void main(...) for android projects. You need to put this in an Activity.