Issue
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": "[email protected]",
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 !
Solution
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
}
Answered By - Gaurav Jeswani
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.