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?
- Interfaz de importación json de Java para Android / Java
- Simple analizar JSON de URL en Android y mostrar en listview
- Androide estudio Logcat muestra datos json en una sola línea y parte de los datos
- UnitTest JSONObject muestra null
- JSON: Parser de corriente de Jackson - ¿realmente vale la pena?
- ¿Está google gson funcionando en android?
- Obtener una matriz de CLAVES para cada elemento bajo jsonarray
- Envío de datos JSON de Android a PHP y escritura a archivo de texto
- Cómo leer el archivo json de la carpeta de activos cuando se prueba por Espresso?
- Convertir JSONArray a Array de cadenas
- Cómo probar si un JSONObject es nulo o no existe
- ArrayAdapter: Los datos de Json se enviarán a spinner
- Cómo mantener múltiples google-service.json en Android Studio
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); }
- ¿Qué es el Native Development Kit (NDK) de Android?
- Diferentes nombres de aplicación para diferentes sabores de creación?