我在 Stack 中多次看到这个问题,但没有运气。问题是,我使用这个 API 来验证我的 CNPJ 字段,如果我有连接,响应将是字段“nome”并填充我的 textview 字段。
到目前为止一切顺利,JSON 是有效的(已在 jsonformatter 中传递),但我无法通过 JSONArray 获取对象,当我设法通过 JSONObject 找到它时,它告诉我无法转换为 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]",
日志
org.json.JSONException:值 GOOGLE BRASIL INTERNET LTDA。在 org.json.JSON.typeMismatch(JSON.java:101) 处无法将 java.lang.String 类型的名称转换为 JSONObject
使用的网址
https://www.receitaws.com.br/v1/cnpj/06990590000123
有人可以帮我解决这个问题吗?谢谢 !
在您的 JSON 中,nome
是字符串类型。所以不要getJSONObject
使用JSONObject类中的getString
方法。所以你的代码应该如下所示:
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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句