java - Convertir InputStream a JSONObject
inputstream to string (10)
Dado que ya está utilizando la biblioteca Json-Simple
Google, puede analizar el json desde un InputStream
como este:
InputStream inputStream = ... //Read from a file, or a HttpRequest, or whatever.
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject)jsonParser.parse(
new InputStreamReader(inputStream, "UTF-8"));
Estoy convirtiendo InputStream a JSONObject usando el siguiente código. Mi pregunta es, ¿hay alguna manera simple de convertir InputStream a JSONObject. Sin hacer InputStream -> BufferedReader -> StringBuilder -> loop -> JSONObject.toString ().
InputStream inputStreamObject = PositionKeeperRequestTest.class.getResourceAsStream(jsonFileName);
BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStreamObject, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
JSONObject jsonObject = new JSONObject(responseStrBuilder.toString());
Este codigo funciona
BufferedReader bR = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
StringBuilder responseStrBuilder = new StringBuilder();
while((line = bR.readLine()) != null){
responseStrBuilder.append(line);
}
inputStream.close();
JSONObject result= new JSONObject(responseStrBuilder.toString());
Esto funcionó para mí:
JSONArray jsonarr = (JSONArray) new JSONParser().parse(new InputStreamReader(Nameofclass.class.getResourceAsStream(pathToJSONFile)));
JSONObject jsonobj = (JSONObject) new JSONParser().parse(new InputStreamReader(Nameofclass.class.getResourceAsStream(pathToJSONFile)));
La mejor solución en mi opinión es encapsular el InputStream en un objeto JSONTokener. Algo como esto:
JSONObject jsonObject = new JSONObject(new JSONTokener(inputStream));
Otra solución: use flexjson.jar: http://mvnrepository.com/artifact/net.sf.flexjson/flexjson/3.2
List<yourEntity> yourEntityList = deserializer.deserialize(new InputStreamReader(input));
Podrías usar una Entidad:
FileEntity entity = new FileEntity(jsonFile, "application/json");
String jsonString = EntityUtils.toString(entity)
Puede utilizar esta api https://code.google.com/p/google-gson/
Es simple y muy útil,
A continuación, le indicamos cómo usar la https://code.google.com/p/google-gson/ Api para resolver su problema
public class Test {
public static void main(String... strings) throws FileNotFoundException {
Reader reader = new FileReader(new File("<fullPath>/json.js"));
JsonElement elem = new JsonParser().parse(reader);
Gson gson = new GsonBuilder().create();
TestObject o = gson.fromJson(elem, TestObject.class);
System.out.println(o);
}
}
class TestObject{
public String fName;
public String lName;
public String toString() {
return fName +" "+lName;
}
}
Contenido del archivo json.js:
{"fName":"Mohamed",
"lName":"Ali"
}
Si no quieres meterte con bibliotecas listas, puedes crear una clase como esta.
public class JsonConverter {
//Your class here, or you can define it in the constructor
Class requestclass = PositionKeeperRequestTest.class;
//Filename
String jsonFileName;
//constructor
public myJson(String jsonFileName){
this.jsonFileName = jsonFileName;
}
//Returns a json object from an input stream
private JSONObject getJsonObject(){
//Create input stream
InputStream inputStreamObject = getRequestclass().getResourceAsStream(jsonFileName);
try {
BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStreamObject, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
JSONObject jsonObject = new JSONObject(responseStrBuilder.toString());
//returns the json object
return jsonObject;
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
//if something went wrong, return null
return null;
}
private Class getRequestclass(){
return requestclass;
}
}
Entonces, puedes usarlo así:
JSONObject jObject = new JsonConverter(FILE_NAME).getJsonObject();
Solución simple:
JsonElement element = new JsonParser().parse(new InputStreamReader(inputStream));
JSONObject jsonObject = new JSONObject(element.getAsJsonObject().toString());
use JsonReader para analizar InputStream. Ver ejemplo dentro de la API: http://developer.android.com/reference/android/util/JsonReader.html