Esiste un modo più semplice per analizzare JSON da un URL? Ho usato Gson non riesco a trovare alcun utile esempio.Analisi di JSON dall'URL
risposta
In primo luogo è necessario scaricare l'URL (come testo):
private static String readUrl(String urlString) throws Exception { BufferedReader reader = null; try { URL url = new URL(urlString); reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buffer = new StringBuffer(); int read; char[] chars = new char[1024]; while ((read = reader.read(chars)) != -1) buffer.append(chars, 0, read); return buffer.toString(); } finally { if (reader != null) reader.close(); } }
Poi è necessario analizzarlo (e qui si hanno alcune opzioni).
GSON (esempio completo):
static class Item { String title; String link; String description; } static class Page { String title; String link; String description; String language; List<Item> items; } public static void main(String[] args) throws Exception { String json = readUrl("http://www.javascriptkit.com/" + "dhtmltutors/javascriptkit.json"); Gson gson = new Gson(); Page page = gson.fromJson(json, Page.class); System.out.println(page.title); for (Item item : page.items) System.out.println(" " + item.title); }
Uscite:
javascriptkit.com Document Text Resizer JavaScript Reference- Keyboard/ Mouse Buttons Events Dynamically loading an external JavaScript or CSS file
Prova API java da json.org:
try { JSONObject json = new JSONObject(readUrl("...")); String title = (String) json.get("title"); ... } catch (JSONException e) { e.printStackTrace(); }
Potreste usare org.apache.commons.io.IOUtils per il download e per l'analisi org.json.JSONTokener:
JSONObject jo = (JSONObject) new JSONTokener(IOUtils.toString(new URL("http://gdata.youtube.com/feeds/api/videos/SIFL9qfmu5U?alt=json"))).nextValue();
System.out.println(jo.getString("version"));
Penso che devi aggiungere '.openStream()' dopo 'new URL (...)'. Quindi deve apparire così: 'JSONObject jo = (JSONObject) new JSONTokener (IOUtils.toString (new URL (" http://gdata.youtube.com/feeds/api/videos/SIFL9qfmu5U?alt=json ") .openStream())). nextValue(); ' – Selphiron
@ Selphiron, funziona perfettamente. Molte grazie. – mahi
Ecco un metodo semplice.
Prima di analizzare il JSON da url -
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
quindi inserire un compito e poi leggere il valore desiderato da JSON -
private class ReadPlacesFeedTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
return readJSONFeed(urls[0]);
}
protected void onPostExecute(String result) {
JSONObject json;
try {
json = new JSONObject(result);
////CREATE A JSON OBJECT////
JSONObject data = json.getJSONObject("JSON OBJECT NAME");
////GET A STRING////
String title = data.getString("");
//Similarly you can get other types of data
//Replace String to the desired data type like int or boolean etc.
} catch (JSONException e1) {
e1.printStackTrace();
}
//GETTINGS DATA FROM JSON ARRAY//
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray postalCodesItems = new JSONArray(
jsonObject.getString("postalCodes"));
JSONObject postalCodesItem = postalCodesItems
.getJSONObject(1);
} catch (Exception e) {
Log.d("ReadPlacesFeedTask", e.getLocalizedMessage());
}
}
}
È possibile quindi inserire un compito come questo -
new ReadPlacesFeedTask()
.execute("JSON URL");
Una semplice soluzione alternativa:
incollare l'URL in un JSON al convertitore csv
Aprire il file CSV sia in Excel o Open Office
Utilizzare gli strumenti di foglio di calcolo per analizzare i dati
Questa è una risposta di qualità molto bassa. Non penso che l'uso di Excel sia una soluzione complessa a questo problema. –
promozione di un convertitore da json a csv forse? – zundi
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.io.FileUtils;
import groovy.json.JsonSlurper;
import java.io.File;
tmpDir = "/defineYourTmpDir"
URL url = new URL("http://yourOwnURL.com/file.json");
String path = tmpDir + "/tmpRemoteJson" + ".json";
remoteJsonFile = new File(path);
remoteJsonFile.deleteOnExit();
FileUtils.copyURLToFile(url, remoteJsonFile);
String fileTMPPath = remoteJsonFile.getPath();
def inputTMPFile = new File(fileTMPPath);
remoteParsedJson = new JsonSlurper().parseText(inputTMPFile.text);
public static TargetClassJson downloadPaletteJson(String url) throws IOException {
if (StringUtils.isBlank(url)) {
return null;
}
String genreJson = IOUtils.toString(new URL(url).openStream());
return new Gson().fromJson(genreJson, TargetClassJson.class);
}
GSON ha un costruttore th a prende un oggetto Reader: fromJson(Reader json, Class classOfT).
Ciò significa che è possibile creare un Reader da un URL e quindi passarlo a Gson per consumare il flusso e effettuare la deserializzazione.
Solo tre righe del codice pertinente.
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Map;
import com.google.gson.Gson;
public class GsonFetchNetworkJson {
public static void main(String[] ignored) throws Exception {
URL url = new URL("https://httpbin.org/get?color=red&shape=oval");
InputStreamReader reader = new InputStreamReader(url.openStream());
MyDto dto = new Gson().fromJson(reader, MyDto.class);
// using the deserialized object
System.out.println(dto.headers);
System.out.println(dto.args);
System.out.println(dto.origin);
System.out.println(dto.url);
}
private class MyDto {
Map<String, String> headers;
Map<String, String> args;
String origin;
String url;
}
}
cosa succede se il json - args ha gli elementi dell'array? –
@Sundar: per gli array si usa TypeToken: https://stackoverflow.com/a/10292824/191246 – ccpizza
ho usare Java 1.8 con com.fasterxml.jackson.databind.ObjectMapper
ObjectMapper mapper = new ObjectMapper();
Integer value = mapper.readValue(new URL("your url here"), Integer.class);
Integer.class può essere anche un tipo complesso. Per esempio usato.
- 1. Errore di analisi JSON
- 2. JQuery di analisi JSON serie
- 3. Analisi e generazione di JSON
- 4. Percorso file di analisi JSON
- 5. di analisi JSON file Java
- 6. Analisi annidato JSON
- 7. Python - Analisi JSON Data Set
- 8. Analisi dell'API JSON in C#
- 9. Analisi di JSON in Java senza conoscere il formato JSON
- 10. JSON problema di analisi non risolto
- 11. analisi di un array Ruby per JSON
- 12. jQuery.ajax() + oggetto JSON vuoto = errore di analisi
- 13. errori di analisi JSON utilizzando Newtonsoft.Json
- 14. MongoDB + Java - analisi di JSON tramite com.mongodb.util.JSON.parse
- 15. JsonPath Errore di analisi JSON in java
- 16. di analisi JSON array con PHP foreach
- 17. Analisi di mappe/dizionari JSON con Gson?
- 18. di analisi JSON Inserisci richiesta C#
- 19. Analisi di JSON utilizzando l'eccezione AFNetworking 2.0
- 20. Analisi di Google Geocoding JSON con PHP
- 21. errore di analisi json con virgolette
- 22. Analisi dei dati JSON con C#
- 23. C# Richiesta e analisi GET JSON
- 24. Analisi dei dati JSON nidificati utilizzando GSON
- 25. mancante] dopo elenco elemento analisi JSON
- 26. Analisi della stringa JSON in Java
- 27. Analisi dell'oggetto JSON in Salesforce Apex
- 28. Come scrivere una classe di analisi JSON di base
- 29. Analisi di un array di oggetti JSON utilizzando Jackson 2.0
- 30. analisi di un array di oggetti JSON in Excel VBA
Hai un esempio? –
per esempio sarà come questo http://gdata.youtube.com/feeds/api/videos/SIFL9qfmu5U?alt=json o dal grafico facebook – Peril