This question already has answers here:
org.json.JSON Exception : End of input at character 0
(4 answers)
Closed 6 years ago.
When the URL is ran manually in browser, this JSON is returned.
{
"error": false,
"0": {
"question": "Using the information that 6.7 × 52 = 348.4, Find the value of: 6.7 × 520",
"useranswer": "3484",
"correctanswer": "3484",
"correct": "1"
},
"1": {
"question": "Jane drives 50mph. London is 350 miles away. How long will it take?",
"useranswer": "5",
"correctanswer": "7",
"correct": "0"
},
"2": {
"question": "74*3?",
"useranswer": "222",
"correctanswer": "222",
"correct": "1"
},
"3": {
"question": "39+31?",
"useranswer": "70",
"correctanswer": "70",
"correct": "1"
}
}
The code is as follows:
public List<String> GetTestResultsFromUserID(Integer userID){
BufferedReader bufferedReader = null;
try {
URL url = new URL(AppConfig.Results_URL + "?userid=" + userID);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty ("Authorization", "Basic Z2FycmV0dGg6ZnJBc3Rpbmc0");
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String result;
result = bufferedReader.readLine();
return ProcessResultSetFromDatabase(result);
}catch(Exception e){
Log.d("Exception in try", "Exception" + e.toString());
return null;
}
}
And then the result is processed here:
private List<String> ProcessResultSetFromDatabase(String result){
List<String> resultSet = new ArrayList<String>();
try{
JSONObject jObj = new JSONObject(result);
boolean error = jObj.getBoolean("error");
if (!error){
for (int i=0; i<48; i++){
JSONObject rSet = jObj.getJSONObject(Integer.toString(i));
resultSet.add("Q: "+rSet.getString("question")+" Correct Ans: "+rSet.getString("correctanswer")+" Given Ans: "+rSet.getString("useranswer")+" Correct:"+(rSet.getString("correct")));
}
}else{
resultSet.add("No results at the moment");
}
}catch(JSONException e){
e.printStackTrace();
}
return resultSet;
}
Note: The result passed to ProcessResultSetFromDatabase seems to be null when passed.
Your JSON output is in "0":{"question": String and you pass integer, So you need to convert int to string.
for (int i=0; i<48; i++){
int tmpInt = i;
String str= String.valueOf(i);
JSONObject rSet = jObj.getJSONObject(str);
resultSet.add("Q: "+rSet.getString("question")+" Correct Ans: "+rSet.getString("correctanswer")+" Given Ans: "+rSet.getString("useranswer")+" Correct:"+(rSet.getString("correct")));
}
You should parse your data using Iterator.
JSONObject jObj = new JSONObject(result);
if (jObj.length() > 0) {
Iterator<String> keys = jObj.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject json= jObj.optJSONObject(key);
Log.e("json", json.toString());
if (json!= null) {
resultSet.add("Q: "+json.getString("question")+" Correct Ans: "+json.getString("correctanswer")+" Given Ans: "+json.getString("useranswer")+" Correct:"+(json.getString("correct")));
}
}
}
Related
Below I have my code for a search request. As yelp only allows to get only 50 results I have a problem to make it work.
So basically offset = 0 and limit = 50 will bring me the results 0-50
offset = 50 and limit = 50 will bring me the results 51-100
So and in my case I need 1000 Results. How can I manage it? I tried everything in my power and now I need some help.
public class Search2 {
static HttpURLConnection conn;
public static void Searche() {
int offset = 0;
int limit = 50;
try {
for (int i = 0; i < 950; i=+50) {
URL url = new URL("https://api.yelp.com/v3/businesses/search?location=" + gui.Lead_1.tFOrt.getText()
+ "&categories=" + gui.Lead_1.tFKeyword.getText() + "&offset=" + i + "&limit=50");
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
}
try {
conn.setRequestProperty("Authorization", "Bearer " + dbb.Pfad.getPath() + " ");
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// throwing the error message if the response is not available.
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
// capturing the response and appending it to the response string.
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
StringBuffer response = new StringBuffer();
while ((output = br.readLine()) != null) {
response.append(output);
}
// converting the response to the JSONObject.
JSONObject jsonObj = new JSONObject(response.toString());
JSONArray list1 = new JSONArray();
JSONArray arr = jsonObj.getJSONArray("businesses");
JSONObject details = new JSONObject();
// capturing the specific values(name, rating, reviewcount) from the response
for (int i = 0; i < arr.length(); i++) {
String name = arr.getJSONObject(i).getString("name");
int rating = arr.getJSONObject(i).getInt("rating");
int review_count = arr.getJSONObject(i).getInt("review_count");
JSONObject address = arr.getJSONObject(i).getJSONObject("location");
details.put("Name", name);
details.put("Rating", rating);
details.put("Review Count", review_count);
details.put("Address", address);
JSONObject object = new JSONObject();
object.put("restaurant " + (i + 1), details);
list1.put(object);
Lead_2.row[0]=i+1;
Lead_2.row[1]=arr.getJSONObject(i).getString("name");
Lead_2.row[2]=arr.getJSONObject(i).getJSONObject("location").getString("address1");
Lead_2.model.addRow(Lead_2.row);
}
I have a JSON File, showing the following:
{
"version": 2,
"locations": [{
"id": "750",
"geo": {
"name": "Lord Howe Island",
"state": "Lord Howe Island",
"country": {
"id": "au",
"name": "Australia"
},
"latitude": -31.557,
"longitude": 159.086
},
"astronomy": {
"objects": [{
"name": "moon",
"days": [{
"date": "2018-09-05",
"events": [],
"moonphase": "waningcrescent"
}]
}]
}
}]
}
I am attempting to show in a TextView the following fields:
name "Lord Howe Island"
latitude "-31.557"
longitude "159.086"
moonphase "waningcrescent"
I have tried the following:
JSONArray JA = new JSONArray(data);
for (int i = 0; i < JA.length(); i++){
JSONObject JO = (JSONObject) JA.get(i);
singleParsed = "Name:" + JO.get("name") + "\n" +
"Latitude:" + JO.get("latitude") + "\n" +
"Longitude:" + JO.get("longitude") + "\n" +
"Phase: " + JO.get("moonphase") + "\n";
}
But unfortunately I do not receive any results.
What am I doing wrong? Thanks very much for any help.
Edit - Full Code for assistance.
public class fetchData extends AsyncTask<Void, Void, Void> {
String data = "";
String dataParsed = "";
String singleParsed = "";
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("example.com"); //Replace with API URL
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null){
line = bufferedReader.readLine();
data = data + line;
}
JSONArray JA = new JSONArray(data);
for (int i = 0; i < JA.length(); i++) {
JSONObject JO = (JSONObject) JA.get(i);
JSONObject geo = JO.getJSONObject("geo");
JSONObject astronomy = JO.getJSONObject("astronomy");
singleParsed = "Name:" + geo.get("name") + "\n" +
"Latitude:" + JO.get("latitude") + "\n" +
"Longitude:" + JO.get("longitude") + "\n" +
"Phase: " + astronomy.get("moonphase") + "\n";
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.fetcheddata.setText(this.data);
}
}
Try this
JSONObject data=new JSONObject(data);
JSONArray JA = data.getJSONArray("locations");
for (int i = 0; i < JA.length(); i++){
JSONObject JO = (JSONObject) JA.get(i);
JSONObject geo=JO.getJSONObject("geo");
JSONObject astronomy=JO.getJSONObject("astronomy");
singleParsed = "Name:" + geo.get("name") + "\n" +
"Latitude:" + JO.get("latitude") + "\n" +
"Longitude:" + JO.get("longitude") + "\n" +
"Phase: " + astronomy.get("moonphase") + "\n";
instead of parsing JSON on your own use gson
Gson gson= new Gson();
YourBeanClass yourBeanClass gson.fromJson(jsonString,YourBeanClass.class)
Json to Java POJO
From above you can get as Bean class just use it to parse your Json.Using POJO to parse json is easy and less vulnerable to error/exception.
For your Json i tried getting the bean object and tried parsing.
And your code will also be more readable:
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("example.com"); //Replace with API URL
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null){
line = bufferedReader.readLine();
data = data + line;
}
Gson gson= new Gson();
YourBeanClass yourBeanClass gson.fromJson(jsonString,YourBeanClass.class)
//get and set all your data here from your bean
String country=yourBeanClass.getCountry()
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Your json parsing is wrong.First of all there is just one object in your json array there is no need of the for loop. You can access it directly using 0th index.
Second
JSONObject JO = (JSONObject) JA.get(i);
This line just gave you the 1st json object inside the array. You have to do one more step to fetch the name.
JSONObject geo=JO.getJSONObject("geo");
Now fetch the name from geo object.
"Name:" + geo.getString("name") + "\n"
Also remember your moonphase string is part of different array. So you need to parse that accordingly
You have to get value of the type defined in your json.For eg. for getting string type it will be
jsonObject.getString("key");
for integer it will be
jsonObject.getInt("key")
I'm having an SQL exception while i'm trying to parse a JSON object. Here's my code snippet.
public JSONArray paymentMode(String stringObjects) throws SQLException {
JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
//JSONOBJECT RETURN
JSONObject jsonObjectReturn = JSONFactoryUtil.createJSONObject();
JSONObject obj = JSONFactoryUtil.createJSONObject();
JSONArray array = JSONFactoryUtil.createJSONArray();
Session session = null;
Connection conn = null;
CallableStatement callableStatement = null;
try {
// test
BeanLocator beanLocator = PortletBeanLocatorUtil
.getBeanLocator("Mrcos-services-portlet");
BasicDataSource bds = (BasicDataSource) beanLocator
.locate("mrcosDataSourceTarget");
conn = (Connection) bds.getConnection();
jsonObject = JSONFactoryUtil.createJSONObject(stringObjects);
JSONArray jsonArray = jsonObject.getJSONArray("dataArray");
for (int i = 0; i < jsonArray.length(); i++) {
obj = jsonArray.getJSONObject(i);
callableStatement = (CallableStatement) conn
.prepareCall("{call PaymentModeSPv2(?,?,?,?,?,?,?,?,?,?,?,?,?)}");
callableStatement.setString(1, jsonObject.getString("mode"));
callableStatement.setString(2, jsonObject.getString("num1"));
callableStatement.setString(3, jsonObject.getString("date1"));
callableStatement.setString(4, jsonObject.getString("num2"));
callableStatement.setString(5, jsonObject.getString("date2"));
callableStatement.setString(6, jsonObject.getString("remarks"));
callableStatement.setDouble(7, jsonObject.getDouble("amount"));
callableStatement.setString(8, jsonObject.getString("receipt"));
callableStatement.setString(9, jsonObject.getString("algo"));
callableStatement.setString(10, jsonObject.getString("code"));
callableStatement.setString(11, jsonObject.getString("address"));
callableStatement.setString(12, jsonObject.getString("status"));
callableStatement.registerOutParameter(13, Types.INTEGER);
callableStatement.executeQuery();
String xreturn = callableStatement.getString(13);
jsonObjectReturn = JSONFactoryUtil.createJSONObject();
jsonObjectReturn.put("xreturn", xreturn);
array.put(jsonObjectReturn);
System.out.println("jsonObjectReturn : " + jsonObjectReturn);
}
return array;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (callableStatement != null) {
callableStatement.close();
}
if (conn != null) {
conn.close();
}
closeSession(session);
}
jsonObjectReturn = JSONFactoryUtil.createJSONObject();
jsonObjectReturn.put("result", "NO RESULTS FOUND!");
return array;
}
I'm having an error at callableStatement.setDouble(7, jsonObject.getDouble("amount")); saying java.sql.SQLException: 'NaN' is not a valid numeric or approximate numeric value.
The amount is decimal in my database. I also tried to use float instead of double but still gives the same error message. I also tried to pass an integer and a decimal number but still the same error occurs. Please help I'm stuck for a while now. Thank you!
You're getting a javascript [NaN][1] in jsonObject.getDouble("amount"). So you need to deal with it somehow. E.g. you can replace it with 0 or Double.NaN:
String amt = jsonObject.getString("amount");
Double amount = "NaN".equals(amt) ? Double.NaN : Double.parseDouble(amt);
callableStatement.setDouble(7, amount);
I am getting the following error on logcat when I run my application. I had many errors before which I have managed to resolve after doing some research. However, this one I am unable to figure out:
03-04 02:52:29.475: E/JustDealsUtils(1913): Error parsing to json on getJarrayFromString(); org.json.JSONException: Expected ':' after result at character 8 of {result}
EDIT 1:
The error now is:
Error parsing to json on getJarrayFromString(); org.json.JSONException: Value result of type java.lang.String cannot be converted to JSONArray
Also linked to this is error for fillproductlist()
Here is my Java Code for this:
public void onTaskCompleted(String result) {
try {
if(result!=""){
// the remote php link
// converting the response into json array
Log.i(DEBUG, result);
jarray = utils.getJarrayFromString(result);
// number of rows in total for a query
int mysqlSize = (jarray.getJSONObject(0).getInt("numRows"));
Log.i(DEBUG, "From " + from + " to " + mysqlSize);
// to check if all the rows are parsed from the mysql
if(from <= mysqlSize){
int rows;
// to check if there is 0
if(jarray.length()>0){
Log.i(DEBUG, "From " + from + " to " + Math.floor(mysqlSize/nr)*nr);
if(from+5<=Math.floor(mysqlSize/nr)*nr){
rows = jarray.length();
}else{
rows = mysqlSize%nr+1;
Utils.IS_ENDED_PRODUCT_LIST = true;
}
ArrayList<String> list = new ArrayList<String>();
for(int i=1; i<rows; i++){
JSONObject row = jarray.getJSONObject(i);
bid.add(row.getInt("bid"));
bTitle.add(row.getString("bTitle"));
bCode.add(row.getString("bCode"));
bPrice.add(row.getString("bPrice") + "£");
bDescription.add(row.getString("bDescription"));
bModule.add(row.getString("bModule"));
bImage.add(Utils.PATH + row.getString("bImage"));
list.add(row.getString("bImage"));
// to check if an id already exists in the db or to create one if doesn't exist
if(!db.hasIDBooks(row.getInt("bid"))) db.createRowOnBooks(row.getInt("bid"), row.getString("bTitle"), row.getString("bCode"), row.getString("bPrice"), row.getString("bDescription"), row.getString("bModule"), Utils.PATH + row.getString("bImage"), row.getString("bSpecialOffer"), row.getInt("bSpecialDiscount"), row.getString("bDateAdded"));
Log.i(DEBUG, row.getString("bDescription"));
}
new DownloadImages(list, bAdapter).execute();
}
}
postParameters.removeAll(postParameters);
}else{
Utils.IS_ENDED_PRODUCT_LIST = true;
if(rlLoading.isShown()){
rlLoading.startAnimation(fadeOut());
rlLoading.setVisibility(View.INVISIBLE);
}
}
} catch (Exception e) {
Log.e(DEBUG, "Error at fillProductList(): " + e.toString());
}
}
});
task.execute();
}else{
// if internet connectio is not available
// then, rows will be fetched from the local sqllite database stored on the android phone
if(db.size(justdealsDatabase.TABLE_BOOKS) > 0){
Cursor cursor = db.getBooksRows(justdealsDatabase.TABLE_BOOKS);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
bid.add(cursor.getInt(cursor.getColumnIndex(justdealsDatabase.KEY_BID)));
bTitle.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BTITLE)));
bCode.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BCODE)));
bPrice.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BPRICE))+ "£");
bDescription.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BDESCRIPTION)));
bModule.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BMODULE)));
bImage.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BIMAGE)));
cursor.moveToNext();
}
bAdapter.notifyDataSetChanged();
Utils.IS_ENDED_PRODUCT_LIST = true;
}
}
}
MY JSON ARRAY CODE ( FULL EDIT 2):
public String getJsonFromUrl(String url){
// to initialise the objects
InputStream is = null;
String result = "";
//making HTTP POST request
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){
Log.e(DEBUG, "Error getJsonFromUrl: " + e.toString());
}
// Converting to String
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"), 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){
Log.e(DEBUG, "Error converting the response to string getJsonFromUrl: " + e.toString());
}
return result;
}
/**
* To convert the string recieved into json object
* result refers to the string that will be converted
* #return will return the json array
*/
public JSONArray getJarrayFromString(String result){
// Parsing string to JSON Array
try{
jarray = new JSONArray("result");
}catch(JSONException e){
Log.e(DEBUG, "Error parsing to json on getJarrayFromString(); " + e.toString());
}
return jarray;
}
And My PHP API (EDIT 1):
<?php
include("MysqlConnection.php");
header('Content-Type: application/json');
$from = $_POST["from"];
$nr = $_POST["nr"];
// those variables are for search
$title = $_POST["title"];
$code = $_POST["code"];
$price = $_POST["price"];
$module = $_POST["module"];
$order = $_POST["order"];
$by = $_POST["by"];
$sql = "SET CHARACTER SET utf8";
$db->query($sql);
// if those 2 var are set then we order the query after them
if(isset($order) && isset($by)){
$sql .= " ORDER BY `$order` $by LIMIT $from, $nr";
}else{
$sql .= "LIMIT $from, $nr";
}
$query = $db->query($sql);
$rows = array();
$rows[] = array("numRows"=>$db->numRows($query));
if($db->numRows($query)!=0){
while($row = mysql_fetch_assoc($query)) {
$rows[] = $row;
}
echo(json_encode($rows));
}
}
$db->closeConnection();
?>
I have implemented all the suggestions recommended by you guys, still there is no luck in getting this code work!!!!
I AM NOT SURE WHY VALUE OF 'RESULT' STRING CANNOT BE CONVERTED INTO JSONARRAY????
I have shown you the JSON ARRAY Declaration, RESULT STRING DECLARATION as well as PHP (See Above for edited versions)
you have to use echo not print_r
echo json_encode($rows);
print_r gives output in array format.
You have send the result two times you have to send the result only one time with encoded
remove the following code and try
echo json_encode($rows);
Maybe you should name your array without "{}" symbols?
jarray = new JSONArray("result");
instead of
jarray = new JSONArray("{result}");
This is my below code from which I need to parse the JSONObject to get individual items. This is the first time I am working with JSON. So not sure how to parse JSONObject to get the individual items from JSONObject.
try {
String url = service + version + method + ipAddress + format;
StringBuilder builder = new StringBuilder();
httpclient = new DefaultHttpClient();
httpget = new HttpGet(url);
httpget.getRequestLine();
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = entity.getContent();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
for (String line = null; (line = bufferedReader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONObject jsonObject = new JSONObject(builder.toString());
// Now iterate jsonObject to get Latitude,Longitude,City,Country etc etc.
}
} catch (Exception e) {
getLogger().log(LogLevel.ERROR, e.getMessage());
} finally {
bufferedReader.close();
httpclient.getConnectionManager().shutdown();
}
My JSON looks like this:
{
"ipinfo": {
"ip_address": "131.208.128.15",
"ip_type": "Mapped",
"Location": {
"continent": "north america",
"latitude": 30.1,
"longitude": -81.714,
"CountryData": {
"country": "united states",
"country_code": "us"
},
"region": "southeast",
"StateData": {
"state": "florida",
"state_code": "fl"
},
"CityData": {
"city": "fleming island",
"postal_code": "32003",
"time_zone": -5
}
}
}
}
I need to get latitude, longitude, city, state, country, postal_code from the above object. Can anyone provide any suggestion how to do it efficiently?
You can try this it will recursively find all key values in a json object and constructs as a map . You can simply get which key you want from the Map .
public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
try{
JSONObject value = json.getJSONObject(key);
parse(value,out);
}catch(Exception e){
val = json.getString(key);
}
if(val != null){
out.put(key,val);
}
}
return out;
}
public static void main(String[] args) throws JSONException {
String json = "{'ipinfo': {'ip_address': '131.208.128.15','ip_type': 'Mapped','Location': {'continent': 'north america','latitude': 30.1,'longitude': -81.714,'CountryData': {'country': 'united states','country_code': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_code': 'fl'},'CityData': {'city': 'fleming island','postal_code': '32003','time_zone': -5}}}}";
JSONObject object = new JSONObject(json);
JSONObject info = object.getJSONObject("ipinfo");
Map<String,String> out = new HashMap<String, String>();
parse(info,out);
String latitude = out.get("latitude");
String longitude = out.get("longitude");
String city = out.get("city");
String state = out.get("state");
String country = out.get("country");
String postal = out.get("postal_code");
System.out.println("Latitude : " + latitude + " LongiTude : " + longitude + " City : "+city + " State : "+ state + " Country : "+country+" postal "+postal);
System.out.println("ALL VALUE " + out);
}
Output:
Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003
ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1}
How about this?
JSONObject jsonObject = new JSONObject (YOUR_JSON_STRING);
JSONObject ipinfo = jsonObject.getJSONObject ("ipinfo");
String ip_address = ipinfo.getString ("ip_address");
JSONObject location = ipinfo.getJSONObject ("Location");
String latitude = location.getString ("latitude");
System.out.println (latitude);
This sample code using "org.json.JSONObject"