Cómo analizar un flujo de entrada JSON

Estoy utilizando java para llamar a una url que devuelve un objeto JSON:

url = new URL("my URl"); urlInputStream = url.openConnection().getInputStream(); 

¿Cómo puedo convertir la respuesta en forma de cadena y analizarla?

Sugeriría que usted tiene que utilizar un lector para convertir su InputStream adentro.

 BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8")); StringBuilder responseStrBuilder = new StringBuilder(); String inputStr; while ((inputStr = streamReader.readLine()) != null) responseStrBuilder.append(inputStr); new JSONObject(responseStrBuilder.toString()); 

Intenté in.toString () pero devuelve:

 getClass().getName() + '@' + Integer.toHexString(hashCode()) 

(Como la documentación dice que deriva a toString de Object)

Todas las respuestas actuales suponen que está bien tirar todo el JSON a la memoria donde la ventaja de un InputStream es que usted puede leer la entrada poco a poco. Si desea evitar la lectura de todo el archivo Json a la vez, entonces te sugiero que utilice la biblioteca de Jackson (que es mi favorito personal, pero estoy seguro de que otros como Gson tienen funciones similares).

Con Jackson puedes usar un JsonParser para leer una sección a la vez. A continuación se muestra un ejemplo de código que escribí que envuelve la lectura de una matriz de JsonObjects en un iterador. Si sólo quieres ver un ejemplo de Jackson, mira los métodos initJsonParser, initFirstElement y initNextObject.

 public class JsonObjectIterator implements Iterator<Map<String, Object>>, Closeable { private static final Logger LOG = LoggerFactory.getLogger(JsonObjectIterator.class); private final InputStream inputStream; private JsonParser jsonParser; private boolean isInitialized; private Map<String, Object> nextObject; public JsonObjectIterator(final InputStream inputStream) { this.inputStream = inputStream; this.isInitialized = false; this.nextObject = null; } private void init() { this.initJsonParser(); this.initFirstElement(); this.isInitialized = true; } private void initJsonParser() { final ObjectMapper objectMapper = new ObjectMapper(); final JsonFactory jsonFactory = objectMapper.getFactory(); try { this.jsonParser = jsonFactory.createParser(inputStream); } catch (final IOException e) { LOG.error("There was a problem setting up the JsonParser: " + e.getMessage(), e); throw new RuntimeException("There was a problem setting up the JsonParser: " + e.getMessage(), e); } } private void initFirstElement() { try { // Check that the first element is the start of an array final JsonToken arrayStartToken = this.jsonParser.nextToken(); if (arrayStartToken != JsonToken.START_ARRAY) { throw new IllegalStateException("The first element of the Json structure was expected to be a start array token, but it was: " + arrayStartToken); } // Initialize the first object this.initNextObject(); } catch (final Exception e) { LOG.error("There was a problem initializing the first element of the Json Structure: " + e.getMessage(), e); throw new RuntimeException("There was a problem initializing the first element of the Json Structure: " + e.getMessage(), e); } } private void initNextObject() { try { final JsonToken nextToken = this.jsonParser.nextToken(); // Check for the end of the array which will mean we're done if (nextToken == JsonToken.END_ARRAY) { this.nextObject = null; return; } // Make sure the next token is the start of an object if (nextToken != JsonToken.START_OBJECT) { throw new IllegalStateException("The next token of Json structure was expected to be a start object token, but it was: " + nextToken); } // Get the next product and make sure it's not null this.nextObject = this.jsonParser.readValueAs(new TypeReference<Map<String, Object>>() { }); if (this.nextObject == null) { throw new IllegalStateException("The next parsed object of the Json structure was null"); } } catch (final Exception e) { LOG.error("There was a problem initializing the next Object: " + e.getMessage(), e); throw new RuntimeException("There was a problem initializing the next Object: " + e.getMessage(), e); } } @Override public boolean hasNext() { if (!this.isInitialized) { this.init(); } return this.nextObject != null; } @Override public Map<String, Object> next() { // This method will return the current object and initialize the next object so hasNext will always have knowledge of the current state // Makes sure we're initialized first if (!this.isInitialized) { this.init(); } // Store the current next object for return final Map<String, Object> currentNextObject = this.nextObject; // Initialize the next object this.initNextObject(); return currentNextObject; } @Override public void close() throws IOException { IOUtils.closeQuietly(this.jsonParser); IOUtils.closeQuietly(this.inputStream); } } 

Si no te importa el uso de la memoria, entonces ciertamente sería más fácil de leer el archivo completo y analizarlo como un gran Json como se menciona en otras respuestas.

Use jackson para convertir la entrada de json al mapa u objeto http://jackson.codehaus.org/

También hay algunas otras bibliotecas útiles para json, puedes google: json java

Utilice una biblioteca.

  • GSON
  • Jackson
  • O una de muchas otras bibliotecas JSON que están ahí fuera.

Para aquellos que señalaron el hecho de que no puede utilizar el método toString de InputStream como este, consulte https://stackoverflow.com/a/5445161/1304830 :

Mi respuesta correcta sería entonces:

 import org.json.JSONObject; public static String convertStreamToString(java.io.InputStream is) { java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } ... JSONObject json = new JSONObject(convertStreamToString(url.openStream()); 

Si desea utilizar Jackson Databind (que Spring utiliza de forma predeterminada para sus HttpMessageConverters ), puede utilizar la API ObjectMapper.readTree (InputStream) . Por ejemplo,

 ObjectMapper mapper = new ObjectMapper(); JsonNode json = mapper.readTree(myInputStream); 
 { InputStream is = HTTPClient.get(url); InputStreamReader reader = new InputStreamReader(is); JSONTokener tokenizer = new JSONTokener(reader); JSONObject jsonObject = new JSONObject(tokenizer); } 
  • Crear json en android
  • Leer la carpeta JSON de / assets en un ArrayList en Android?
  • Cómo Caché los datos de Json para estar disponibles sin conexión?
  • JSON Error "java.lang.IllegalStateException: Se esperaba BEGIN_OBJECT pero era STRING en la línea 1 de la columna 1 ruta $"
  • Función de parada que llama en pestañas
  • Enviando cadena UTF-8 usando HttpURLConnection
  • Cómo enviar datos de formulario en retrofit2 android
  • Respuesta de JSON de Django en Android
  • JSONObject.toString: cómo no escapar de barras
  • Mensaje de error 'java.net.SocketException: socket failed: EACCES (Permiso denegado)'
  • Conversión de cadena a json objeto android
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.