Convert InputStream to JSONObject
Solution 1
Since you're already using Google's Json-Simple
library, you can parse the json from an InputStream
like this:
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"));
Solution 2
use JsonReader in order to parse the InputStream. See example inside the API: http://developer.android.com/reference/android/util/JsonReader.html
Solution 3
If you don't want to mess with ready libraries you can just make a class like this.
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;
}
}
Then, you can use it like this:
JSONObject jObject = new JsonConverter(FILE_NAME).getJsonObject();
Solution 4
This code works
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());
Solution 5
You can use this api https://code.google.com/p/google-gson/
It's simple and very useful,
Here's how to use the https://code.google.com/p/google-gson/ Api to resolve your problem
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;
}
}
json.js file content :
{"fName":"Mohamed",
"lName":"Ali"
}
AAV
Updated on August 18, 2021Comments
-
AAV almost 3 years
I am converting InputStream to JSONObject using following code. My question is, is there any simple way to convert InputStream to JSONObject. Without doing 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());
-
Sotirios Delimanolis about 10 yearsDoes
FileEntity
expect aFile
or aURL
or aInputStream
? They seem to be getting theInputStream
from the classpath. -
Blackbelt about 10 yearsa File, and the content type. What you mean with "They seem to be getting the InputStream from the classpath"? @SotiriosDelimanolis
-
Sotirios Delimanolis about 10 yearsThey are using
Class#getResourceAsStream()
which returns anInputStream
for a resource on the classpath. They don't have aFile
here. -
Sotirios Delimanolis about 10 yearsThis doesn't answer the question. Please specify how Gson fixes their issue.
-
Sotirios Delimanolis about 10 yearsThis doesn't answer the question. Please specify how those libraries fixes OP's issue.
-
zero298 about 10 yearsAlso, if the library the questioner is already using offers a solution, try to utilize that library with that solution. If it doesn't, then express that don't make an answer that basically says "use another library" and then post links to the library. Answers need to explain the links they have associated, not just be link dumps.
-
user1601201 about 8 yearsThis should be the accepted answer... the code in the link is simply: JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
-
Aleks G over 7 yearsIt's (almost) a link-only answer. You'd be much better off by including the gist in your answer.
-
haxxxton over 7 yearsPlease provide some context to your answer, specifically what it is doing, and why it solves the problem.
-
Gabor almost 6 yearsJsonParser is not available
-
Daniele Zagnoni over 5 yearswhat do you mean? For using JSONTokener you must add java-json dependency (the same for JSONObject, which is the main topic of this question...)
-
Vinci about 5 yearsdunno why, but this code throws an exception: Exception in thread "main" java.lang.ClassCastException: class org.json.simple.JSONArray cannot be cast to class org.json.JSONObject (org.json.simple.JSONArray and org.json.JSONObject are in unnamed module of loader 'app')
-
friederbluemle over 4 yearsThe constructor of
JSONTokener
that comes with the Android framework does not take anInputStream
. OnlyString
. -
CodeToLife about 4 yearsto get string:
BufferedReader in = new BufferedReader(new InputStreamReader( con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); String targetLcl=response.toString();
-
klutt about 2 yearsShould this be
JsonParser
instead ofJSONParser
?