JSONTokener: A JSONObject text must begin with '{' - java

Hitting exception in my code below for using JSON on a URI
public static String processRestResponse(String language){
URI uri = null;
JSONTokener tokener = null;
try {
uri = new URI("https://api.github.com/search/repositories?q=language:Java");
URL url = uri.toURL();
InputStream inputStream = url.openStream();
tokener = new JSONTokener(inputStream.toString());
JSONObject root = new JSONObject(tokener);
} catch (Exception e) {
e.printStackTrace();
}
Exception as follows...
org.json.JSONException: A JSONObject text must begin with '{' at character 1
at org.json.JSONTokener.syntaxError(JSONTokener.java:410)
at org.json.JSONObject.<init>(JSONObject.java:179)
at Assignment1.processRestResponse(Assignment1.java:48)
at Assignment1.main(Assignment1.java:108)
Is there an alternative approach i can take that would suit?

make sure you read the the InputStream correctly using the right charset, for example like this:
StringBuilder textBuilder = new StringBuilder();
try (Reader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName(StandardCharsets.UTF_8.name())))) {
int c = 0;
while ((c = reader.read()) != -1) {
textBuilder.append((char) c);
}
}
afteron you can use it:
tokener = new JSONTokener(textBuilder.toString());
JSONObject root = new JSONObject(tokener);

Related

cannot convert Json string to JSONObject or JSONArray

i have created a rest wcf web service and hosted in local iis, the json string is converted with JsonConvert.SerializeObject(object) of Newtonsoft package.
the output of the web service is
"[{\"companyId\":2,\"companyName\":\"A\"},
{\"companyId\":8,\"companyName\":\"B\"}]"
this web service is consume by android apps,
i tried with JSONArray and JSONObject but it keep on throwing exception
org.json.JSONException: Expected literal value at character 2 of
[{\"companyId\":2,\"companyName\":\"A\"},{\"companyId\":8,\"companyName\":\"B\"}]
org.json.JSONException: Expected literal value at character 2 of
"[{\"companyId\":2,\"companyName\":\"A\"},
{\"companyId\":8,\"companyName\":\"B\"}]"
org.json.JSONException: Value [{"companyId":2,"companyName":"A"},
{"companyId":8,"companyName":"B"}] of type java.lang.String cannot be
converted to JSONArray
this is the code in android class
public JSONArray RequestWebService(URL urlToRequest) {
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
urlConnection.setReadTimeout(RETRIEVE_TIMEOUT);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
int statusCode = urlConnection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_OK) {
InputStream in = new BufferedInputStream(
urlConnection.getInputStream());
String result = getResponseText(in);
//result = result.substring(1, result.length() - 1);
//result = result.replace("/\\/g", "");
JSONArray j = new JSONArray(result);
return j
}
return null;
}
private String getResponseText(InputStream inStream) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader rd = null;
try{
rd = new BufferedReader(new InputStreamReader(inStream));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
}finally {
if (rd != null) {
rd.close();
}
}
return sb.toString();
}
String response = "Your Response";
try{
JsonArray jAry = new JsonArray(response);
JsonObjct jObj;
for(int i=0;i<jAry.length;i++){
jObj = JAry.getJsonObject(i);
// You can get your string from object jobj and also use it by store it value in arraylist.
}
} catch(Exception e){
}

how to convert string data into json?

here string data values comes from shell script code.i need to show this resultant values in json format
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(new String[]{"/home/admin/institutestatus.sh"});
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while ((line = input.readLine()) != null) {
Gson gson =new Gson();
System.out.println(gson.toJson(line));
}
} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
JSONArray arr = new JSONArray();
while ((line = input.readLine()) != null) {
JSONObject obj = new JSONObject();
obj.put("value",line);
arr.add(obj);
}
I've used this function to convert InputStream to String and the to JSONObject.
public static String load(final InputStream in) {
String data = "";
try {
InputStreamReader is = new InputStreamReader(in, Charset.forName("UTF-8"));
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(is);
String read = br.readLine();
while (read != null) {
sb.append(read);
read = br.readLine();
}
data = sb.toString();
} catch (IOException e) {
System.out.println(e.getMessage());
}
return data;
}
You use the GSON in order to don't have to work with the Strings in the first place...

Transfering Base64 String over Http REST service with JSON response

I have a webservice that returnds a json response , the json response contains both plain text and base64 encoded images , I am consuming that service using android app so I implemented progress bar to indicate the progress .
Implementing progress bar forces me to use BufferedInputStream to read the response and update the progress based on what the app is reading .
The problem is that everything is working fine and the progress is updating correctly, but after collecting the response and exiting the while loop , I try to convert the string into json format using JSONObject.
Here is the code snippet
BufferedInputStream bis = new BufferedInputStream(responseEntity.getContent());
StringBuilder sb = new StringBuilder();
String line = null;
int total = 0 ;
int count = 0 ;
byte[] buffer = new byte[4096];
StringBuffer sBuffer = new StringBuffer();
StringWriter sw = new StringWriter();
String content = new String();
while((count = bis.read(buffer)) > 0){
content += new String(buffer,Charset.defaultCharset());
total += count;
publishProgress(""+(int )total*100/this.contentSize);
Log.i("updating",""+(int )total*100/this.contentSize);
}
bis.close();
// String content = new String(sb);
// Log.i("ServerRawresponse",content);
try {
Log.i("REsponse_Content",content.replaceAll("\"", ""));
responseString = new JSONObject(new JSONTokener(content.replaceAll("\"", "\\\"")));
//System.out.println(content);
} catch (JSONException e) {
e.printStackTrace();
}
Any help please
Try this methods works perfectly with me
HttpResponse WSresponse = httpclient.execute(httppost);
String response = getResponseBody(WSresponse.getEntity());
JSONObject jobj = new JSONObject(response);
public String getResponseBody(final HttpEntity entity) throws IOException, ParseException {
System.out.println("GEN START : " + Calendar.getInstance().getTimeInMillis());
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
if (instream == null) {
return "";
}
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException(
"HTTP entity too large to be buffered in memory");
}
StringBuilder buffer = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream, HTTP.UTF_8));
String line = null;
try {
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} finally {
instream.close();
reader.close();
}
return buffer.toString();
}

getJsonStringFromURL() return a null string

I'm trying to get a json string from a url and my method is returning a null string value when I use this line of code:
String jsonStr = getJsonStringFromURL(url);
Here is the method I'm using:
public static String getJsonStringFromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jsonObject = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch (Exception e) {
return null;
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
catch(Exception e) {
return null;
}
return result;
}
I have a url variable used where when I copy and paste the url into a browser it does return and display a json string. Any suggestions or help would be greatly appreciated.
The thing is you assigning value to the result when BufferReader is closed. Thats why you getting the null value.
Instead of assigning result = sb.toString(); outside of the BufferReader assign it before closing it.
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
System.out.println(result);// It will print you the value
is.close();
Hope it helps.

Creating JSONObject from text file

I am attempting to read a text file and create a JSONObject in an Android application, but after reading the text file into a string, I get a JSONException thrown when I try to construct a JSONObject using the string.
Here is the code I am using:
InputStream is = this.getResources().openRawResource(R.raw.quiz);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String jsString = "";
String line = null;
while((line = reader.readLine()) != null){
jsString += line;
}
is.close();
reader.close();
try {
return new JSONObject(jsString);
} catch (JSONException e) {
}
return null;
Here is the text file I am reading from, quiz.txt:
{"length":3,"questions":[{"questionText":"Is mayonaise an instrument?","answers":["Yes","no","no","no","no"],"correctAnswer":0},{"questionText":"10^2","answers":["1","10","100","1000","over 9000"],"correctAnswer":1},{"questionText":"Dogs Name?","answers":["Barky","Steve","Rex","Daisy","Wormy"],"correctAnswer":3}]}
Try using this method to read the file contents into a string.
public static String getJsonFromResource( int resource, Context context ) {
InputStream inputStream = context.getResources().openRawResource( resource );
BufferedReader r = new BufferedReader( new InputStreamReader( inputStream ) );
StringBuilder stringBuilder = new StringBuilder();
String line;
String jsonString = null;
try {
while (( line = r.readLine() ) != null) {
stringBuilder.append( line );
}
jsonString = stringBuilder.toString();
}
catch (Exception e) {
Log.e( "GetJsonFromResource", Log.getStackTraceString( e ) );
}
return jsonString;
}

Categories