I'm getting W/System.err: org.json.JSONException: Value when running this code to get the JSON. However, when I use:
[{"name":"Abhishek","password":"123","contact":"1111111111","country":"India"},{"name":"Rahul","password":"1s","contact":"1sdfsdf","country":"India"},{"name":"Abhishek","password":"aar","contact":"asdbsfg","country":"India"}]
(https://api.myjson.com/bins/j5f6b), a tester JSON URL, it gives me the output.
I have tried changing it to JSON Object in places but that isn't helping.
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("http://www.free-map.org.uk/fm/ws/bsvr.php?
bbox=-0.73,51.04,-0.71,51.06&way=highway&format=json");
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);
singleParsed = "name:" + JO.get("name") + "\n";
dataParsed = dataParsed + singleParsed +**"\n"** ;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
twod.data.setText(this.dataParsed);
}
I expect a name output and am currently getting nothing but W/System.err: org.json.JSONException:
The problem seems to be with your parsing logic.
Check this:
JSONObject jsonObject = new JSONObject(data);
JSONArray JA = jsonObject.getJSONArray("features");
for (int i = 0; i < JA.length(); i++) {
JSONObject JO = (JSONObject) JA.get(i);
System.out.print(JO);
}
You have to create a JSONObject first, later extract the JSONArray from it.
Related
Hi I am working on a project it will show USD EUR TRY Bitcoin Gold values i have api for all of this values in json i want to sort them out my json link is this https://canlidoviz.com/doviz-kurlari.jsonld
I am parsing the json with this class
public class ClassJSONParser {
private InputStream is = null;
private JSONObject jObj = null;
private String json = "";
public ClassJSONParser(){
}
public JSONObject getJSONFromURL(String url) {
try {
URL urlObject = new java.net.URL(url);
HttpURLConnection conn=(HttpURLConnection) urlObject.openConnection();
conn.setRequestMethod("GET");
is = new BufferedInputStream(conn.getInputStream());
} catch (IOException e){
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
StringBuilder sb = new StringBuilder();
String line;
while ((line=reader.readLine())!=null){
String tmp = line + "/n";
sb.append(tmp);
}
is.close();
json=sb.toString();
}catch (Exception e){
Log.i("Buffer Error","Error Converting Result"+e.toString());
}
try {
if(json !=null){
jObj=new JSONObject(json);
}else{
jObj=null;
}
}catch (JSONException e){
}
return jObj;
}
}
and getting a string like this
ClassJSONParser jParser = new ClassJSONParser();
String url = "https://canlidoviz.com/doviz-kurlari.jsonld";
jsonO= jParser.getJSONFromURL(url);
Log.d("***",jsonO.toString());
what method should i use how can i do can you give me guidance
I have built a php script who give me my JSON data of my mysql database, but in android studio I don't know how I can put my data in a ArrayList of String
I have tested many possibilities but no one works,
If you have any idea about my code it can be very good
ArrayList<String> ListeFamilles = new ArrayList<>(15);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.selectionneracteactivity);
HttpURLConnection urlConnection = null;
StringBuilder result = new StringBuilder();
try {
URL url = new URL("http://192.168.1.26:8888/GetNomFamille.php");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
ListeFamille.add(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
JSON:
[{"Famille":"TEXT1"},{"Famille":"TEXT2"},{"Famille":"TEXT3"},{"Famille":"TEXT4"},{"Famille":"TEXT5"},{"Famille":"TEXT6"},{"Famille":"TEXT7"},{"Famille":"TEXT8"},{"Famille":"TEXT9"},{"Famille":"TEXT10"},{"Famille":"TEXT11"},{"Famille":"TEXT12"},{"Famille":"TEXT13"},{"Famille":"TEXT14"},{"Famille":"TEXT15"}]
PHP:
<?php
mysql_connect("localhost","root","password");
mysql_select_db("mydb");
$sql=mysql_query("SELECT Famille FROM FAMILLES");
$rows = array();
while($r=mysql_fetch_assoc($sql)){
$rows[] = $r;
}
print json_encode($rows);
mysql_close();
?>
You should not do network connection in mainthread, Read this article and try to add it in asynctask,
For Json parsing after getting the value you can try this,
StringBuilder result = new StringBuilder();
ArrayList<String> listOfValues = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(result.toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.optJSONObject(i);
if(jsonObject == null) {
continue;
}
String jsonValue = jsonObject.optString("Famille");
listOfValues.add(jsonValue);
}
} catch (JSONException e) {
e.printStackTrace();
}
I've been following a tutorial which provided an example website to use in the json request, however when i put in my own website to scrape data from, nothing happens.
Here is my code;
private TextView tvData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData = (TextView) findViewById(R.id.tvJsonItem);
new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesDemoItem.txt");
}
public class JSONTask extends AsyncTask<String,String, String>{
#Override
protected String doInBackground(String ... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies");
JSONObject finalObject = parentArray.getJSONObject(0);
String ChampionName = finalObject.getString("movie");
String mostGames = finalObject.getString("year");
return ChampionName + mostGames;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
tvData.setText(result);
}
}
}
Screen of when it works on left and screen when it doesnt work on right.
So yeah, this is what i know i have to change
new JSONTask().execute("http://api.champion.gg/champion/Ekko");
and
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("WHAT DO I PUT HERE");
JSONObject finalObject = parentArray.getJSONObject(0);
String ChampionName = finalObject.getString("WHAT DO I PUT HERE");
String mostGames = finalObject.getString("WHAT DO I PUT HERE");
From this URL - http://api.champion.gg/champion/Ekko/ , i want to get lets say the first two fields "key":"Ekko","role":"Top", so if anyone could give me a hand, that would be great!
According to the JSON returned form your link http://api.champion.gg/champion/Ekko/
You have to start to parse your string response as JSONArray
JSONArray parentObject = new JSONArray(finalJson);
then start to loop through this array to get JSONObject
JSONObject jsonObject = parentObject.getJSONObject(yourLoopIndex);
Inside each JSONObject you can get any value. by using the key in the original JSON string.
I got this Excepion for two days
"org.json.JSONException: Value Exception of type java.lang.String cannot be converted to JSONArray",
I searched the net but I can't resolve it.
It gives me the desirable response in the browser but I don't know what's the matter with android !
Please help me.
Here is my code
private class SigninActivity extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... arg0) {
String newString="";
try {
String tonTexte = loginDisplay.getText().toString();
String tonTexte1 = passDisplay.getText().toString();
String link = "http://192.168.56.1/projects/stage/atelier.php";
String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(tonTexte, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(tonTexte1, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"),8);
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
sb.append(line);
break;
}
return sb.substring(sb.indexOf("{"),sb.lastIndexOf("}") + 1);
}
catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
TextView a = (TextView) findViewById(R.id.aff);
JSONObject json_data=null;
TextView b = (TextView) findViewById(R.id.aff1);
//recuperation des donnees json
try{
//String jsonObjRecv = JSONGet.getJSONfromURL(URL_LIST);
if(!TextUtils.isEmpty(result)) {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
Log.i("log_tag", "cin: " + json_data.getString("nom"));
donnees.add(json_data.getString("nom"));
donnees1.add(json_data.getString("atelier"));
}
for (String elem : donnees) {
a.setText(elem);
}
for (String elem : donnees1) {
b.setText(elem);
}
}
else{
Log.w("json", "result is null");
}
}
catch(JSONException e){
Log.i("tagjsonexp",""+e.toString());
}
catch (ParseException e) {
Log.i("tagjsonpars", "" + e.toString());
}
}
}
and here is the php code
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$base = mysql_connect ('localhost', 'root', '');
mysql_select_db ('stage', $base) ;
$output=array();
$username = $_POST['username'];
$password = $_POST['password'];
$sql=mysql_query("SELECT CIN FROM authentification where login= '".$username."' AND password = '".$password. "'");
//$sql=mysql_query("SELECT CIN FROM authentification where login= 'amani' AND password = '123' ");
if (!$sql) {
die(mysql_error());
}
while($data = mysql_fetch_array($sql))
{
$a=$data['CIN'];
}
$sql1=mysql_query("SELECT nom,atelier FROM controlleur where CIN= '".$a."'");
while($row=mysql_fetch_assoc($sql1))
{
$output[]=$row;
//print(json_encode(array($output));
print(json_encode(array("NomTableau" => $output)));
mysql_close();
?>
Assuming your PHP script is producing correct JSON. Try changing this part
JSONArray jArray = new JSONArray(result);
to this.
JSONObject jObject = new JSONObject(result);
JSONArray jArray = jObject.getJSONArray("NomTableau");
Here is a sample of my json_encode in PHP:
print(json_encode($row));
leads to {"AverageRating":"4.3"} which is good.
But in Java, I can not seem to grab this 4.3 value. Here it is (for an Android project) I have edited non-relevant data.
public class Rate extends ListActivity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
String Item, Ratings, Review, starAvg;
RatingBar ratingsBar;
ArrayList<NameValuePair> param;
public void onCreate(Bundle savedInstanceState) {
starAvg = "0"; // Sets to 0 in case there are no ratings yet.
new starRatingTask().execute();
ratingsBar = (RatingBar) findViewById(R.id.theRatingBar);
class starRatingTask extends AsyncTask<String, String, Void> {
InputStream is = null;
String result = "";
#Override
protected Void doInBackground(String... params) {
String url_select = "http://www.---.com/---/average_stars.php";
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("item", Item));
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
String starAvgTwo = null;
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
starAvg = json_data.getString("AverageRating");
starAvgTwo = starAvg;
}
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "No Star Ratings!",
Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
Toast.makeText(getBaseContext(), starAvgTwo,
Toast.LENGTH_LONG).show();
ratingsBar.setRating(Float.valueOf(starAvg));
}
}
That second toast produces a blank (I assume a "" - empty string?). If I change the toast variable back to starAvg, then it toasts "0".
How can I retrieve the value of 4.3.
As we discussed in the comments on the original question, the PHP is sending down as single JSONObject rather than an array. Parsing as a JSONObject is required in it's present state; however, if you begin sending down an array of your value objects, then you'd use JSONArray to parse it.
I think your JSON doesn't contain array. so just do this:
JSONObject jsonObject = new JSONObject(result); //to convert string to be a JSON object
String averageRating = jsonObject.getString("AverageRating"); //get the value of AverageRating variable
and try toast the averageRating.
and how to get the array from JSON object?
if you have JSON:
{"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }]
}
then use this code
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.i(Rate.class.getName(), jsonObject.getString("firstName"));
}
that code will produce
John Anna Peter
in your LogCat