I need to parse json object for this url
I have used following code
private void parse(String url2) throws MalformedURLException, IOException,JSONException {
// TODO Auto-generated method stub
InputStream is = new URL(url2).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
for(int i=0;i<valArray.length();i++)
{
String p = nameArray.getString(i) + "," + valArray.getString(i);
Log.i("p",p);
}
} finally {
is.close();
}
}
private String readAll(BufferedReader rd) throws IOException {
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}}
But I am getting the source of the file in the jsonText String.And as it does not start with a '{' i am getting following error in the log :
org.json.JSONException: A JSONObject text must begin with '{' at character 1>
Looks to me like the issue is with the page you have created to return the response. Is there a particular reason you are using an HTML page with frames? If you browse the page loaded in the frame (http://88.198.1.116:9080/parentconnect/services/student/getStudentDetails?studentid=1&schoolid=1) you will see that the source has the JSON string you are after.
Why are you not browsing to this URL instead of the HTML page?
Based on the fact that the string does not start with a '{' character I would say the json you have is actually invalid and malformed json. Take a look here and here.
I would say your options are to see if you can get the malformed json fixed on the server side, or else on the client do some checks to see if it's malformed and try to fix it before passing the string to the jsonObject parsers.
Related
I am going to get the JSON from the localhost db. Then, I want to put the json into ArrayList. I want to call the parseJSON function. But the JSON is null. Where I should call the function, thanks so much:))
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
StringBuilder sb = new StringBuilder();
InputStream input = con.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
parseJSON(json);
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON(
);
getJSON.execute();
}
private void parseJSON(String json) {
Gson gson = new Gson();
Type type = new TypeToken<List<EssayElement>>(){}.getType();
List<EssayElement> mList = gson.fromJson(json, type);
for (EssayElement essayElement : mList){
Log.i("Message: " +
"", essayElement.id + "-" + essayElement.title + "-" + essayElement.essay + "-" + essayElement.date + "-" + essayElement.time);
}
}
null object reference with String"json"
I would suggest using a proper http library that handles making requests for you like Volley or Retrofit... JSON and Error handling are also builtin, so AsyncTask can completely be removed for that purpose
But what you have is fine, only json shouldn't be used after the while loop, it's only the last line of the http response, not the full json (assuming there's multiple lines)
You should really consider parsing the results in the onPostExecute, and possibly even having the parse method return an actual object, or display to the UI
You are appending the string to StringBuilder sb = new StringBuilder();. You have to call like this parseJSON(sb.toString()); cause String json is just a pointer doesn't hold the actual string, you want.
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
String json = sb.toString();
You can instead use my code snippet it's working fine for me. now you can use son variable for your private void parseJSON(String json) function.
From the endpoint "test" I am returning a JSONObject:
#POST("/test")
#PermitAll
public JSONObject test(String name) {
JSONObject jsonval=new JSONObject();
json.put("key1",true);
json.put("key2","test");
return json;
}
in the method that checks the returned value I want to search for value of "key1".
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json = null;
String res = "";
while ((res = in.readLine()) != null) {
json += res + "\n";
}
in.close();
if (jsonData has key1 with value true){
//do sth
}
else{
//do sth else
}
How can I parse the returned JSONObject?
Have you tried constructing the JSONObject from its string representation (see http://www.json.org/javadoc/org/json/JSONObject.html):
JSONObject result = new JSONObject(json)
where json is the string you've read from the InputStream
Note: you might have to strip the last new line char or even omit new lines altogether
I'm simply trying to create JSON object like that:
JSONObject jsonObject = new JSONObject(new JsonUtility().execute(UrlUtility.url + "/" + lessonUrl).get());
Error occurs here ^ with message received in catch block:
org.json.JSONException: End of input at character 0 of
JsonUtility class as follows (I belive problem lies not there but still):
private class JsonUtility extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String result = "";
try {
InputStream inputStream = new URL(params[0]).openStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
StringBuilder sBuilder = new StringBuilder();
// Reading Json into StringBuilder
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
// Converting Json from StringBuilder to String
result = sBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
You see that response is concatenated from strings (due to application logic). The final string is: http://itvdn-api.azurewebsites.net/api/courses/test-driven-development/tdd-introduction. As you see when I redirect to that link it gives JSON response.
I have tried to evaluate this UrlUtility.url and received that:
That weird ending of char array confuses me. Perhabs its the problem. Tried to replace those characters using String.replaceAll("'\u0000'0", "" ). Didnt work.
Please help. Will appreciate any ideas. Thanks.
EDIT:
Also, when I hardcode link as:
JSONObject jsonObject = new JSONObject(new JsonUtility().execute("http://itvdn-api.azurewebsites.net/api/courses/test-driven-development/tdd-introduction").get());
It works!
EDIT #2 # ρяσѕρєя K
result = sBuilder.toString(); is empty - "" since it can't parse that concatenated string.
Note: I've been using the same parser with different links in this application e.g. http://itvdn-api.azurewebsites.net/api/courses and that was working fine (but there was no concatenation with link)
/**
* Convert InputStream into String
* #param is
* #return
* #throws IOException Throws an IO Exception if input stream cannot be read
*/
public static String stringFromInputStream(InputStream is) throws IOException {
if (is != null) {
byte[] bytes = new byte[1024];
StringBuilder x = new StringBuilder();
int numRead = 0;
while ((numRead = is.read(bytes)) >= 0)
x.append(new String(bytes, 0, numRead));
return x.toString();
}
else {
return "";
}
}
Use this method for reading the inputstream and get the string.
I am passing the following JSON object from a .jsp page to a java servlet using JSON.stringify and JQuery.ajax():
{"bin":[{"binId":"0","binDetails":[{"productCode":"AU192","qty":"4"},{"productCode":"NE823","qty":"8"}],"comments":"store pickup"},{"binId":"1","binDetails":[{"productCode":"AF634","qty":"2"}],"comments":""},{"binId":"2","binDetails":[{"productCode":"QB187","qty":"3"}],"comments":"international shipping"},{"binId":"3","binDetails":[{"productCode":"AF634","qty":"2"},{"productCode":"QB187","qty":"2"}],"comments":""}]}
This is the code in my java servlet:
StringBuffer strBuffer = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while((line = reader.readLine()) != null){
strBuffer.append(line);
}
} catch (Exception e) {
}
try {
JSONObject jsonObj = new JSONObject(new JSONTokener(strBuffer.toString()));
// I call a method here and pass jsonObj
} catch (Exception e) {
}
In the method to which I pass jsonObj I am using jsonObj.length() to find out how many items are in jsonObj and it tells me 1, which in this case I would have expected 3. I even tried this:
JSONObject bins = jsonObj.get("bin");
bins.length();
which told me jsonObj.get("bin") was not a JSONObject. Is my data formatted incorrectly before I pass it from my .jsp or am I using the JSONObject in my java servlet incorrectly? How do I access the values in the JSONObject?
JSONArray bins = jsonObj.getJSONArray("bin");
bins.length();
I want to make an Http request and store the result in a JSONObject. I haven't worked much with servlets, so I am unsure as to whether I am 1) Making the request properly, and 2) supposed to create the JSONObject. I have imported the JSONObject and JSONArray classes, but I don't know where I ought to use them. Here's what I have:
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
//create URL
try {
// With a single string.
URL url = new URL(FEED_URL);
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
}
in.close();
} catch (MalformedURLException e) {
}
catch (IOException e) {
}
My FEED_URL is already written so that it will return a feed formatted for JSON.
This has been getting to me for hours. Thank you very much, you guys are an invaluable resource!
First gather the response into a String:
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuilder fullResponse = new StringBuilder();
String str;
while ((str = in.readLine()) != null) {
fullResponse.append(str);
}
Then, if the string starts with "{", you can use:
JSONObject obj = new JSONObject(fullResponse.toString()); //[1]
and if it starts with "[", you can use:
JSONArray arr = new JSONArray(fullResponse.toStrin()); //[2]
[1] http://json.org/javadoc/org/json/JSONObject.html#JSONObject%28java.lang.String%29
[2] http://json.org/javadoc/org/json/JSONArray.html#JSONArray%28java.lang.String%29
Firstly, this is actually not a servlet problem. You don't have any problems with javax.servlet API. You just have problems with java.net API and the JSON API.
For parsing and formatting JSON strings, I would recommend to use Gson (Google JSON) instead of the legacy JSON API's. It has much better support for generics and nested properties and can convert a JSON string to a fullworthy javabean in a single call.
I've posted a complete code example before here. Hope you find it useful.