I saw this questions a bunch of times here in Stack, but had no luck. The thing is, I'm using this API for validate my CNPJ field, if I have a connection, the response would be the field "nome" and populate my textview field.
So far so good, the JSON is valid (already passed in jsonformatter) but I can't the object through JSONArray and when I manage to find it by JSONObject it tells me that can't be converted to String.
valide.setOnClickListener(view1 -> {
//String PJ = cnpj.getText().toString();
String PJ = "06990590000123";
String url = "https://www.receitaws.com.br/v1/cnpj/" + PJ;
jsonParse(url);
});
private void jsonParse(String url) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
String json;
#Override
public void onResponse(JSONObject response) {
try {
json = response.getJSONObject("nome").toString();
razao.append(json);
razao.setText(json);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Invalid ! ", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError erro) {
erro.printStackTrace();
}
});
mQueue.add(request); //Volley.newRequestQueue
}
JSON
{ "atividade_principal": [ { "text": "Portais, provedores de conteúdo e outros serviços de informação na internet", "code": "63.19-4-00" } ],
"data_situacao": "01/09/2004",
"complemento": "ANDAR 17A20 TSUL 2 17A20", "tipo": "MATRIZ",
**"nome": "GOOGLE BRASIL INTERNET LTDA.", //Need this field**
"uf": "SP",
"telefone": "(11) 2395-8400",
"email": "googlebrasil#google.com",
LOG
org.json.JSONException: Value GOOGLE BRASIL INTERNET LTDA. at nome of
type java.lang.String cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:101)
URL USED
https://www.receitaws.com.br/v1/cnpj/06990590000123
Can someone help me with this problem, please ? Thank you !
In your JSON the nome is of type String. So rather than getJSONObject use getString method from JSONObject class. So your code should be like below:
private void jsonParse(String url) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
String json;
#Override
public void onResponse(JSONObject response) {
try {
json = response.getString("nome"); // Here is the change
razao.append(json);
razao.setText(json);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Invalid ! ", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError erro) {
erro.printStackTrace();
}
});
mQueue.add(request); //Volley.newRequestQueue
}
Try this:
First construct JsonObject and then get the string value of the key.
JSONObject jsonObject = new JSONObject(json);
String valueIWanted = jsonObject.getString("nome"))
Related
im using android valley library, currently im only able to post simple json, im struggling in posting nested json format like this :
{
"user": {
"email": "digest#example.com",
"password": "thedigest123"
it looks like i didnt know how to format the nested json for this case, could you help me?
here's my java class that i used to connect my web api
public void login(String email, String password) {
String url = BASE_URL + "api/session";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("email", email);
jsonObject.put("password", password);
Response.Listener<JSONObject> successListener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(mApplication, "Success", Toast.LENGTH_SHORT).show();
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mApplication, "Error", Toast.LENGTH_SHORT).show();
}
};
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, jsonObject, successListener, errorListener);
mRequestQueue.add(request);
}
catch (JSONException e) {
Toast.makeText(mApplication, "JSON exception", Toast.LENGTH_SHORT).show();
}
}
Create dto classes for your request body:
public class UserRequestDTO{
private UserDto user;
//getters, setters
}
public class UserDto{
private String email;
private String password;
}
Convert it to json string using Gson lib:
public static String stringify(Object obj) {
Gson gson = new Gson();
String jsonString = gson.toJson(obj);
return jsonString;
}
Then convert it to StringEntity with new StringEntity(stringify(new UserRequestDto(/*params*/), "UTF-8");
or to JSONObject with new JSONObject(stringify(new UserRequestDto(/*params*/));, and use it in your request.
If you don't want the overhead of Gson or creating classes (unless you intend to have more complex objects) You can simply do:
JSONObject userJsonObject = new JSONObject("{ \"user\": {\"email\": \"" + email + "\", \"password\": \"" + password + "\" } }");
I send the /getsms GET request to an API and I get the expected results on postman. However, when I try to make the same request through volley in java on android studio, it just doesn't get a response, I keep waiting and nothing happens.
I'm sure the API does get the request since the expected changes occur when I send the data associated with the get request.
So I'm at a loss as to why exactly it doesn't get a response.
Java code:
final String url = "http://10.0.2.2:3000/myroute/getsms/"+frm;
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
try {
String frm = response.getString("src_num");
String msg = response.getString("msg");
int id = response.getInt("id");
itemsAdapter.add(frm + ": " + msg);
Log.d("Response", response.toString());
}
catch (Exception err) {
Log.d("excpetion", err.toString());
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
API code:
router.get('/getsms/:dest_num', function (req, res) {
console.log("get oldest unsent sms from db");
let sql = "SELECT * FROM " + table + " WHERE " + "dest_num=" + req.params.dest_num + " AND sent=FALSE " + "ORDER BY id " + "LIMIT 1;";
console.log(sql);
db.mycon.query(sql, function (err, result) {
console.log("Result: " + JSON.stringify(result));
if(err){
res.send(err);
} else {
console.log("SENT!")
res.json(result);
}
});
});
Any help is appreciated.
UPDATE: So upon sifting through the logs I found this:
2020-01-15 22:07:23.481 11880-11880/com.example.sms D/Error.Response: com.android.volley.ParseError: org.json.JSONException: Value [{"id":4,"src_num":"321","dest_num":"1003435365","msg":"first message from server","time":100,"sent":0}] of type org.json.JSONArray cannot be converted to JSONObject
Apparently the response is received but Volley kicks when parsing. I cant see why this is happening. I don't see anything wrong with the JSON string. And is this really enough for it to not go into the onResponse function?
UPDATE2: So apparently that was indeed the problem and what was sent wasn't a JSONObject but a JSONArray. and just needed to change the datatypes accordingly.
So the code ended working with:
String url = "http://10.0.2.2:3000/myroute/getsms/" + frm;
JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response_arr) {
try {
JSONObject response = response_arr.getJSONObject(0);
String frm = response.getString("src_num");
String msg = response.getString("msg");
int id = response.getInt("id");
itemsAdapter.add(frm + ": " + msg);
} catch (Exception err) {
System.out.println(err.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
});
requestQueue.add(jsonObjectRequest);
Thanks to the comments for helping :)
You can try for The code given below and also add the request to the requestqueue of the new instance of RequestHandler.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response); //here is the mistake of parsing which will be removed after it is converted to the json object
JSONObject object = array.getJSONObject(0); //-----mistake
String frm = object.getString("src_num");
String msg = object.getString("msg");
int id = object.getInt("id");
itemsAdapter.add(frm + ": " + msg);
Log.d("Response", response.toString());
} catch (JSONException e) {
Log.d("excpetion", err.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.response", err.toString());
}
});
new RequestHandler().addToRequestQueue(stringRequest);
Hope it helps !!
I want to send JsonObjectRequest to Laravel. But I am facing this problem:
E/Volley: [239] BasicNetwork.performRequest: Unexpected response code
500 for http://10.0.2.2:8000/req
I have searched on the internet but I could not find an answer to this problem.
My Java code:
public void loginUser(String email, String password, final OnLoginResponse onLoginResponse){
JSONObject requestJsonObject=new JSONObject();
try {
requestJsonObject.put("email",email);
requestJsonObject.put("password",password);
JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, "http://10.0.2.2:8000/req",requestJsonObject , new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
request.setRetryPolicy(new DefaultRetryPolicy(18000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(context).add(request);
} catch (JSONException e) {
Log.e(TAG, "loginUser: "+e.toString());
}
}
My Laravel code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ReqDemoController extends Controller
{
public function getData(Request $request){
$data = $request->json()->all();
$email = $data->input('email');
$pass = $data->input('password');
DB::table('login')->insert([
'email' => $email,
'password' => $pass
]);
}
}
I'm trying to make a post request and get a string that my server generates as a response. I get this error: D/Error.Response: com.android.volley.ParseError: org.json.JSONException: Value GVL7TY of type java.lang.String cannot be converted to JSONObject. the GVL7TY value is the generated code from the server. I'm new to android and I don't know how to fix it. appreciate your help!
private void sendRequest(final String email, final String name,String url,RequestQueue queue) {
JSONObject request = new JSONObject();
try
{
request.put("TeacherEmail", email);
request.put("ClassName", name);
}
catch(Exception e)
{
e.printStackTrace();
}
JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, url, request,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject responseObj) {
// response
Log.d("Response", responseObj.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
) {
};
queue.add(postRequest);
}
The response returned from your server is not valid json. Try debuging the raw response.
I got an jsonarray like:
[{
"color": -1,
"fill": false,
"id": 1,
"radius": 154.613,
"shapeText": "",
"shapeType": "circle",
"x1": 141.172,
"x2": 0,
"y1": 231.188,
"y2": 0
}, {
"color": -4569601,
"fill": false,
"id": 2,
"radius": 0,
"shapeText": "",
"shapeType": "rectangle",
"x1": 512.656,
"x2": 606.781,
"y1": 305.25,
"y2": 413.502
}]
and I try to do POST to the server but I fail :[
I already get an jsonarray frm the server and I also did POST but for jsonobject to the server but I couldn't make it POST Jsonarray :[, anyone got any idea how to do it?
public class JSONPostArrayRequest extends JsonRequest<JSONObject> {
JSONArray params;
public JSONPostArrayRequest(String url, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener, JSONArray params) {
super(Method.POST, url, null, listener, errorListener);
this.params=params;
}
#Override
public byte[] getBody() {
if ( this.params != null && this.params.length() > 0) {
return encodeParameters( this.params, getParamsEncoding());
}
return null;
}
private byte[] encodeParameters(JSONArray params, String paramsEncoding) {
try {
return params.toString().getBytes(paramsEncoding);
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
}
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString =
new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
and my request done with this code:
public void updateDraw(ArrayList<Shape> shapes) {
JSONArray jsonArrayShapes = new JSONArray();
Log.d("START OF JSON ARRAY ", shapes.toString());
for (Shape shape : shapes) {
try {
JSONObject jsonObjectShape = new JSONObject();
jsonObjectShape.put("color", String.valueOf(shape.getColor()));
jsonObjectShape.put("fill", String.valueOf(shape.isFill()));
jsonObjectShape.put("radius", String.valueOf(shape.getRadius()));
jsonObjectShape.put("shapeText", String.valueOf(shape.getShapeText()));
jsonObjectShape.put("shapeType", String.valueOf(shape.getShapeType()));
jsonObjectShape.put("x1", String.valueOf(shape.getX1()));
jsonObjectShape.put("x2", String.valueOf(shape.getX2()));
jsonObjectShape.put("y1", String.valueOf(shape.getY1()));
jsonObjectShape.put("y2", String.valueOf(shape.getY2()));
jsonObjectShape.put("id", String.valueOf(shape.getId()));
jsonArrayShapes.put(jsonObjectShape);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("JSONARRAY = ", jsonArrayShapes.toString());
}
String shapeUrl = Main.GROUPS_URL + "/" + id + "/shape";
Log.d("URL = ", shapeUrl);
JSONPostArrayRequest jsonPostArrayRequest = new JSONPostArrayRequest(shapeUrl,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("onErrorResponse ", error.toString());
}
}, jsonArrayShapes);
requestQueue.add(jsonPostArrayRequest);
}
You aren't passing your JSONArray into the request.
super(Method.POST, url, null, listener, errorListener);
That null parameter, as per the documentation
A JSONArray to post with the request. Null is allowed and indicates no parameters will be posted along with request.
Therefore, I don't see why you need to extend JsonRequest, or especially why you typed it with <JSONObject>.
The JsonArrayRequest class already exists, you just need to give the JSONArray object as the third parameter there.