why I am having double '[[' ?
should it be one bracket ? '['
[[{"name":"50 shade of
gray","path":"http://api.androidhive.info/json/movies/1.jpg","description":"long
story","likes":"5","comments":" Very
nice"},{"name":"Transformers","path":"http://api.androidhive.info/json/movies/2jpg","description":"Robots","likes":"7","comments":"
beautiful"},{"name":"Avangeers","path":"http://api.androidhive.info/json/movies/3.jpg","description":"hulk
and iron man","likes":"8","comments":" wow"}]]
this is my php
$sql = "select name , path , description , likes , comments from image ";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('name'=>$row[0],
'path'=>$row[1],
'description'=>$row[2],
'likes'=>$row[3],
'comments'=>$row[4]
));
}
echo json_encode(array($result));
mysqli_close($con);
And is it correct getting it in such code ?
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("r", response.toString());
hidePDialog();
System.out.print(response);
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("name"));
movie.setThumbnailUrl(obj.getString("path"));
movie.setRating(obj.getString("description"));
// movie.setRating(((Number) obj.get("description"))
// .doubleValue());
movie.setYear(obj.getString("likes"));
// movie.setYear(obj.getInt("likes"));
// Genre is json array
JSONArray genreArry = obj.getJSONArray("comments");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.print(error);
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
$result is an array.
You push associative arrays (that become objects) in that array, so now you have [{...},{...}]
Then you do:
echo json_encode(array($result));
so you get an array with an array in it, resulting in the above result with extra '[' around: [[{...},{...}]]
Related
I can parse json from an url in this way:
String link1 = "http://www.url.com/test1.json";
String link2 = "http://www.url.com/test2.json";
private void fetchMovies() {
String url = link1;
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() > 0) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("title");
Movie m = new Movie(rank, title);
movieList.add(0, m);
} catch (JSONException e) {
}
}
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
MyApplication.getInstance().addToRequestQueue(req);
}
I want to parse my json from multiple url.
I want to parse url1 and url2 at the same time.
How can I do that?
Why don't you use "links" as array ?
In case you will use an array:
JSONObject jsonObject = new JSONObject();
JSONArray keys = jsonObject.getJSONArray("links");
int length = keys.length();
for (int i = 0; i < length; i++) {
new ReadJSON().execute(keys.getString(i));
}
Anyway, you take all the keys and go one after the other, and then query each
EDIT:
JSONObject jsonObject = new JSONObject(/*Your links json*/);
JSONObject links = jsonObject.get("links");
Iterator<String> keys = links.keys();
while (keys.hasNext()) {
new ReadJSON().execute(links.getString(keys.next()));
}
My app supposedly to send a source and a destination as parameters to get the fastest bus route and then send them back as an array.
I want to make a list from a json array using volley. Here is an example of my array output.
{
"arrayrute":[
"Halte LIK",
"Halte Kampoeng Semarang",
"Halte Kaligawe 2",
"Halte Pasar Kobong",
"Halte Kota Lama"
]
}
How am I supposedly to make a list from it? Usually a json array from a database would have it's row name before the variable so I just have to use list.set_id(jsonobject.getString("id")) or list.set_id(jsonobject.optString("id"))
Here's my java code to get the array
private void getData() {
//Creating a string request
asal = spin_dari.getSelectedItem().toString().trim();
tujuan = spin_ke.getSelectedItem().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.GET, DIRECTION_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
results = j.getJSONArray("arrayrute");
//Calling method getStudents to get the students from the JSON Array
getdireksi(results);
//dirlist.add(results .toString());
} catch (JSONException e) {
e.printStackTrace();
}
adaptdir.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_ASAL,asal);
params.put(KEY_TUJUAN,tujuan);
return params;
}
};
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getdireksi(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
dirlist.add(json.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Please Try with this way. Below is DEMO
String url = "{ \n" +
" \"arrayrute\":[ \n" +
" \"Halte LIK\",\n" +
" \"Halte Kampoeng Semarang\",\n" +
" \"Halte Kaligawe 2\",\n" +
" \"Halte Pasar Kobong\",\n" +
" \"Halte Kota Lama\"\n" +
" ]\n" +
"}";
try {
JSONObject jobject= new JSONObject(url);
JSONArray jarray=jobject.getJSONArray("arrayrute");
for(int k=0;k<jarray.length();k++)
{
String getValue=(jarray.getString(k));
System.out.println("Intellij_Amiyo"+getValue);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
Final
private void getdireksi(JSONArray j)
{
//Traversing through all the items in the json array
for(int k=0;k<j.length();k++)
try {
String getValue=(j.getString(k));
System.out.println("Intellij_Amiyo"+getValue);
dirlist.add(json);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Your getdireksi() method is wrong. Put following code instead of yours.
private void getdireksi(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
String json = j.getString(i);
//Adding the name of the student to array list
dirlist.add(json);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Following guide I see this:
JsonArrayRequest movieReq = new JsonArrayRequest(URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("nome_stanza"));
movie.setThumbnailUrl(obj.getString("icona"));
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController2.getInstance().addToRequestQueue(movieReq); //i need this movieReq
But I don't have a URL where the Jsoncode is collocated, I receive jsoncode from another method that gives me a string like this:
{"risposta_server": [{"nome_stanza":"via oslavia"},{"icona":"http:\/\/****.**.**.**\/fil***\/****\/images\/icon\/icon2.png"},{"Admin":"s"}]}
Then, how can I change the first code to use this result?
I've got mixed up in response, but I understand it's supposed to come Json Object.The next step:
JSONOArray array = response.getJSONArrary("risposta_server");
for (int i = 0; i < array.length(); i++) {
try {
JSONObject obj = array.getJSONObject(i);
Movie movie = new Movie();
if(i == 0){
movie.setTitle(obj.getString("nome_stanza"));
}else if(i == 1){
movie.setThumbnailUrl(obj.getString("icona"));
}
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
...
See the job if I misunderstand.
Maybe you need json encode like json_encode($str) on php script. Where $str is an array list.
So, your server script will be like this
$arr = array('hello', 'world', 'where', 'i', 'life');
echo json_encode($arr);
Then you will get json data from server
this is my request code ,please help me to parse it correctly. I want all the options for each particular question but I am getting only one option .can anyone solve it. I have attached SS of my data format.
JsonObjectRequest request = new JsonObjectRequest(
"http://www.proprofs.com/quiz-school/mobileData/request.php?request=QuizStart&module=handShake&title=does-your-crush-like-you-girls-only_1",
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
hidePDialog();
// ArrayList<Data> listData = new ArrayList<>();
if (response != null && response.length() > 0) {
try {
JSONArray array = response.getJSONArray("quiz");
// JSONObject jsonObject = array.getJSONObject(0);
for (int i = 0; i < array.length(); i++) {
JSONObject currentArray = array.getJSONObject(i);
DataQuestions movie = new DataQuestions();
movie.setQuestion(currentArray.getString("question"));
String question = currentArray.getString("question");
System.out.println("question----------" + question);
movie.setQuesImage(currentArray.getString("QuesImage"));
String image = currentArray.getString("QuesImage");
System.out.println("QuesImage----------" + image);
JSONArray keys= currentArray.getJSONArray("keys");
for(int j =0;j<keys.length();j++){
JSONObject keyobject = keys.getJSONObject(j);
movie.setOption(keyobject.getString("option"));}
/*String key = null;
if(keys.getJSONObject("option")) {
key = keys.getString("option");
}
movie.setOption(key);*/
/* JSONArray jsonArray1 = (jsonObject.getJSONArray("keys"));
int numberOfItemsInResp = jsonArray1.length();
for (int j = 0; j < numberOfItemsInResp; j++) {
JSONObject jsonObject2 = jsonArray1.getJSONObject(j);
DataQuestions options = new DataQuestions();
// movie = new DataQuestions();
options.setOption(jsonObject2.getString("option"));
String optios = jsonObject2.getString("option");
System.out.println("option----------" + options);
// JSONArray jsonArray1 = (response.getJSONArray("keys"));*/
movieList.add(movie);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//If an error occurs that means end of the list has reached
VolleyLog.d(TAG, "Error: " + error.getMessage());
// hidePDialog();
Toast.makeText(MainActivity.this, "No Items Available", Toast.LENGTH_LONG).show();
}
});
request.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(request);
}
This is because, you use a single object in second for loop. You should to define keys object and stored within arraylist in main object. Like this
public class Quiz {
String quizId;
String QuesImage;
String question;
String questionId;
String Type;
int index;
ArrayList<Keys> keysList;
}
public class Keys{
String answerId;
String option;
String AnsImage;
}
and parse it
JSONArray array = response.getJSONArray("quiz");
for (int i = 0; i < array.length(); i++){
JSONObject jsonObj = array.getJSONObject(i);
Quiz quiz = new Quiz();
quiz.QuesImage = jsonObj.getString("QuesImage");
quiz.question = jsonObj.getString("question");
quiz.questionId = jsonObj.getString("questionId");
quiz.Type = jsonObj.getString("Type");
quiz.index = jsonObj.getInt("index");
JSONArray keys = jsonObj.getJSONArray("keys");
for (int j = 0; j < keys.length(); j++) {
JSONObject keysObj = keys.getJSONObject(j);
Keys keys = new Keys();
keys.answerId = keysObj.getString("answerId");
keys.option = keysObj.getString("option");
keys.AnsImage = keysObj.getString("AnsImage");
quiz.keysList.add(keys);
}
}
I was searching a solution but I could not solve it.
thats my JSON
{"Error":"","Filme":[{
"title": "Dawn of the Planet of the Apes",
"image": "http://api.androidhive.info/json/movies/1.jpg",
"rating": 8.3,
"releaseYear": 2014,
"genre": ["Action", "Drama", "Sci-Fi"]
},
{
"title": "District 9",
"image": "http://api.androidhive.info/json/movies/2.jpg",
"rating": 8,
"releaseYear": 2009,
"genre": ["Action", "Sci-Fi", "Thriller"]
},
...
...
}]}
and that's my code
// Movies json url
private static final String url = "https://d....url....";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private HorizontalListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (HorizontalListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url ,new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i).getJSONObject(TAG_MOVIE);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(((Number) obj.get("rating"))
.doubleValue());
movie.setYear(obj.getInt("releaseYear"));
//Genre is json array
JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
but the result is only a white layout. I think it is because my code don't find "Filme" variable in JSON but i don't know how to fix it.
any idea??
Thank you!!
"Filme" is not a JSONObject, it is a JSONArray actually. Simply parse it as a JSONArray :-)
EDIT:
First of all, use a StringRequest, not JSONArray, as the root of what you receive is NOT an JSONArray.
And then, once you have a simple String as a result, do something like this:
JSONObject root = new JSONObject(result);
JSONArray films = root.getJSONArray("Filme");
JSONObject obj;
for (int i = 0; i < films.length(); i++) {
obj = films.getJSONObject(i);
//Put all the parsing for a single Movie JSONObject here
}
Here is the solution that I made with “Kelevandos” help.
Maybe it can help someone.
// Request a string response from the provided URL.
StringRequest movieReq = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Log.d(TAG, response.toString());
hidePDialog();
JSONObject root;
try {
root = new JSONObject(response);
JSONArray films = root.getJSONArray("Filme");
JSONObject obj;
for (int i = 0; i < films.length(); i++) {
obj = films.getJSONObject(i);
//Put all the parsing for a single Movie JSONObject here
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(((Number) obj.get("rating"))
.doubleValue());
movie.setYear(obj.getInt("releaseYear"));
// Genre is json array
JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);