JSONObject不能转换为String



我在Stack上多次看到这个问题,但都没有运气。问题是,我用这个API来验证CNPJ字段,如果我有连接,响应将是字段"无名"并填充我的textview字段。

到目前为止,JSON是有效的(已经在jsonformatter中传递),但我不能通过JSONArray找到对象,当我设法通过JSONObject找到它时,它告诉我不能转换为字符串。

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",
日志
>

org.json。例外:价值谷歌巴西互联网有限公司。在没有type java.lang.String不能转换为JSONObjectorg.json.JSON.typeMismatch (JSON.java: 101)

URL使用

https://www.receitaws.com.br/v1/cnpj/06990590000123

有人能帮我解决这个问题吗?谢谢!

在JSON中,nome是字符串类型。因此,而不是getJSONObject使用getString方法从JSONObject类。所以你的代码应该像下面这样:

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
}

试试这个:首先构造JsonObject,然后获取键的字符串值。

JSONObject jsonObject = new JSONObject(json);
String valueIWanted = jsonObject.getString("nome"))

最新更新