This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 4 years ago.
This is what I have tried:
The database is in my localhost and I am using my own IP.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONArray array = new JSONArray(response);
for (int x = 0; x<array.length();x++){
JSONObject ob = array.getJSONObject(x);
Alumnos list = new Alumnos();
list.setUsername(ob.getString("username"));
list.setJob(ob.getString("job"));
list.setAge(ob.getInt("age"));
alumnos.add(list);
}
updateRecycler(alumnos);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("Error: ", error.toString());
}
}
);
queue.add(stringRequest);
}
I try to show my results in a Recycler view but I get the next error:
10-03 21:41:28.033 10077-10077/? W/System.err: org.json.JSONException: Value {"result":[{"userid":"1","username":"Luis","job":"developer","age":"23"},{"userid":"2","username":"Alejandro","job":"agronomo","age":"24"},{"userid":"3","username":"Gabriel","job":"Redes","age":"24"}]} of type org.json.JSONObject cannot be converted to JSONArray
I think I might be missing something veri obvious because I get the Array in the Logcat.
You are receiving a JSONObject ({})
Your data is inside a JSONArray ([]) i.e. result so use
JSONObject obj = new JSONObject(response);
JSONArray array = obj.getJSONArray("result");
Related
when there is only one object, i dont have problem to retrieve variable from database
but when i want to retrive variable from only user1 or user2 the text in android doesnt appear anything.
this is my array from php code
{"users":[{"id":"5","name":"user1","updated_at":"2020-10-21 13:35:10"},{"id":"6","name":"user2","updated_at":"2020-10-21 11:29:53"}]}
and this my java code
private void getData(String name) {
String tag_string_req = "get";
ArrayList<HashMap<String, String>> list_data;
list_data = new ArrayList<HashMap<String, String>>();
StringRequest strReq = new StringRequest(Method.GET,
AppConfig.URL_GET, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("users");
for (int a = 0; a < jsonArray.length(); a++) {
JSONObject json = jsonArray.getJSONObject(a);
String pengguna = jsonObject.getString("name");
if (pengguna.contains(name)) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("updated_at", json.getString("updated_at"));
list_data.add(map);
}
update_time.setText(list_data.get(0).get("updated_at"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
});
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
my question is how to get specific JSON object based on some variable? so the text in android only show text based on user.
edit : the problem already solved by some edit in php code, so only the object fetching from database based on user.
my response in android
{"users":[{"id":"6","name":"user2","updated_at":"2020-10-21 13:35:10"}]}
the problem right now is the textview doesnt show me the value although the response already correct
You can look up to follow this :
JSONObject jsonObject = new JSONObject();
jsonObject.getJSONObject("key");
It will resolve your problem, I think.
I'm parsing a simple JSON response, and it is working when trying to parse the employer name, but it gets to a point where it will eventually crash and say that my 'review' json object, is empty. Here is the response:
https://raw.githubusercontent.com/vikrama/feed-json-sample/master/feed.json
And here is how I'm reading it:
private void extractName()
{
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest request = new JsonObjectRequest(JSON_URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject gimme = response.getJSONObject("response");
JSONArray resultsArray = gimme.getJSONArray("results");
for(int i = 0; i < resultsArray.length(); i++)
{
JSONObject info = resultsArray.getJSONObject(i);
JSONObject review = info.getJSONObject("review");
Log.d("COMP NAME", review.getString("employerName"));
companyNames.add(review.getString("employerName"));
}
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
adapter = new CompanyAdapter(MainActivity.this, companyNames);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage());
}
});
queue.add(request);
}
The debug line prints the correct values, then abruptly stops saying "no value for review". I'm pretty confused by this because it seems i'm reading through the data correctly. (use https://jsonformatter.org/json-viewer to better format this json i listed above)
Also, everything else in my recyclerview is set up properly, and the method extractName() is being called in the onCreate() method of my main activity.
This is happening because in some JSON Object you don't have "review" object, so it's throwing your code directly to catch Exception.
In order to overcome this, Please use:-
if(info.has("review")) {
JSONObject review = info.getJSONObject("review");
companyNames.add(review.getString("employerName"));
}
Instead of:
JSONObject review = info.getJSONObject("review");
Log.d("COMP NAME", review.getString("employerName"));
companyNames.add(review.getString("employerName"));
I have an API which send me a JSON object when I send a token to the server , I use GET method and I have to send token in body, not headers, it works in postman correctly when I put token in body but I have volley server error in android studio and I entered error response.here is my codes:
ant solution???? please
private void getFreightsFromServer()
{
final String url =" https://parastoo.app/api/driver-cargo-list";
JSONObject jsonData = new JSONObject();
String token = G.getString("token");
try
{
jsonData.put("token", token);
} catch (JSONException e)
{
e.printStackTrace();
}
Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>()
{
boolean isGet = false;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onResponse(JSONObject response)
{
try
{
MyPost post = new MyPost();
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject tempJsonObject = jsonArray.getJSONObject(i);
JSONObject jsonOriginCustomer = new JSONObject(tempJsonObject.getString("origin_customer"));
post.setOriginCity(jsonOriginCustomer.getString("customerCity"));
JSONObject jsonDestinationCustomer = new JSONObject(tempJsonObject.getString("destination_customer"));
Log.d("result", jsonDestinationCustomer.getString("customerCity"));
post.setDestinationCity(jsonDestinationCustomer.getString("customerCity"));
freightsList.add(post);
// isGet = true;
adapter.notifyDataSetChanged();
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
};
Response.ErrorListener errorListener = new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getContext(), error.toString(), Toast.LENGTH_LONG).show();
Log.d("jdbvdc", error.toString());
error.printStackTrace();
}
};
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, jsonData, listener, errorListener);
Log.d("fhdhdcf",jsonData.toString());
final int socketTimeout = 100000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
request.setRetryPolicy(policy);
AppSingleton.getInstance(getContext()).addToRequestQueue(request);
}
Please show the error message you have. Also I am not sure how ok it is to send something in a body of a GET request. This answer might help you:
HTTP GET with request body
It's better to use post method for this type of request.
But still if you want to use GET method then you should have to pass token in the URL.
Below is an example
final String username = etUname.getText().toString().trim();
final String password = etPass.getText().toString().trim();
URLline = "https://demonuts.com/Demonuts/JsonTest/Tennis/loginGETrequest.php?username="+username+"&password="+password;
I am new to Android and JAVA and I am trying to parse a json response. I know how to parse jsonarray but no Idea how to parse jsonobject. Can someone tell me how? Below is my Response.
{"118":{"garment_color":"Blue","garment_name":"skjhkds","garment_price":"232"},"119":{"garment_color":"hjsadjjs","garment_name":"sdasd","garment_price":"23478"}}
And this is how parsed jsonarray.
public void JSON_DATA_WEB_CALL(){
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.INVISIBLE);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitleNamee(json.getString(JSON_IMAGE_TITLE_NAME));
//GetDataAdapter2.setImageServerLarger(json.getString(JSON_IMAGE_LARGER));
GetDataAdapter2.setImageServerUrl(json.getString(JSON_IMAGE_URL));
GetDataAdapter2.setMrp_price(json.getString(JSON_MRP_PRICE));
GetDataAdapter2.setDisc_price(json.getString(JSON_DISC_PRICE));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
Please Someone help. Thanks.
In my opinion, use Gson library, where you give it the json object/array/string and it automatically parses it into a java object. Note that you have to define the java class with the appropriate fields.
EDIT: So here's an answer that goes with the suggested guidelines:
First create your model classes just like you will receive them from the server:
public class MyServerObject {
MyGarment jsonKeyName;
}
public class MyGarment {
String garment_color;
String garment_name;
String garment_price;
}
Next, after receiving your json string, parse it using Gson:
Gson gson = new Gson();
String json= "{"jsonKeyName":{"garment_color":"Blue","garment_name":"skjhkds","garment_price":"232"};
MyServerObject serverObject = gson.fromJson(json, MyServerObject.class);
Now, you can access your Garment object from your server object with all the values parsed correctly. Also note that if you're receiving a json array you could add the object as a list in your MyServerObject.class.
Hope this helps.
as per my above comment
you need to make JSONObject request instead of JSONArray request
try this to parse your JSON Response
try {
JSONObject jsonObject= new JSONObject("Response");
JSONObject jsonObject1=jsonObject.getJSONObject("118");
String garment_color=jsonObject1.getString("garment_color");
String garment_name=jsonObject1.getString("garment_name");
String garment_price=jsonObject1.getString("garment_price");
JSONObject jsonObject2=jsonObject.getJSONObject("119");
String garment_color2=jsonObject1.getString("garment_color");
String garment_name2=jsonObject1.getString("garment_name");
String garment_price2=jsonObject1.getString("garment_price");
} catch (JSONException e) {
e.printStackTrace();
}
Use StringRequest instead of JSONObject/JSONArray request and finally fetch value like this:
JSONObject object = new JSONObject(YOUR JSON RESPONSE);
String s1 = object.getJSONObject("118").getString("garment_color");
i have a problem with get json with volley library.
this is my json:
{"result":1}
the php code count rows in mysql database and show result in this json file.
the number of count is integer.
and this is my code for get this json:
private void getData () {
//url + id of row that want to count
String url = Config.DATA_URL_COUNT +"1";
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//loading.setVisibility(View.INVISIBLE);
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Toast.makeText(this,error.getMessage().toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response) {
int name = 0;
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.TAG_RESULT);
JSONObject collegeData = result.getJSONObject(0);
name = jsonObject.getInt(Config.JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
String count = String.valueOf(name);
rowcount_kargozarybime.setText(count); //insert result in textview
}
and this is my php code:
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$categoryid = $_GET['categoryid'];
define('HOST','144.76.10.250');
define('USER','cp21983_test');
define('PASS','*******');
define('DB','cp21983_marivanjobs');
$con = mysqli_connect(HOST,USER,PASS,DB);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"SET character_set_results=utf8,character_set_client=utf8,character_set_connection=utf8, character_set_database=utf8,character_set_server=utf8");
$sql="SELECT * FROM jobs WHERE categoryid='".$categoryid."'";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
echo json_encode(array("result"=>$rowcount));
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
}
i well be thankfull if anyone can help me.
Try using :
JSONObject respObject = new JSONObject(response);
int result = respObject.getInt("result");
This is a json object,not a json array. therefore use this code to get result count
JSONObject jsonObject = new JSONObject(response);
int count = jsonObject.getInt("result");
rowcount_kargozarybime.setText(String.valueOf(count));