【问题标题】:Get information from an ObjectJson without Array从没有数组的 ObjectJson 中获取信息
【发布时间】:2023-03-22 10:51:01
【问题描述】:

我有下面的类,我可以从 JSONArray 中获取这种格式的信息:

{"cliente":[{"id":"1334","nome":"Bruno"}]}

TextView nome_usuario;

private static final String TAG_CLIENTE = "cliente";
private static final String TAG_NOME = "nome";

JSONArray cliente = null;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
Bundle savedInstanceState) {
View grafico = inflater.inflate(R.layout.fragment_fragment_perfil, container, false);
nome_usuario = (TextView ) grafico.findViewById(R.id.txtNome);
new JSONParse().execute();
return grafico;
}


private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(getActivity());
    pDialog.setMessage("Atualizando");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(true);
    pDialog.show();

}

@Override
protected JSONObject doInBackground(String... args) {
    JSONParser jParser = new JSONParser();
        JSONObject json = jParser.getJSONFromUrl("url do json");
        return json;

}
@Override
protected void onPostExecute(JSONObject json) {
    pDialog.dismiss();
    try {
        cliente = json.getJSONArray(TAG_CLIENTE);
        JSONObject c = cliente.getJSONObject(0);
        String nome = c.getString(TAG_NOME);
        nome_usuario.setText(nome);
    } catch (JSONException e) {
        e.printStackTrace();
    }


}
}

}

但现在我想使用以下格式的 json:

{"name": "布鲁诺"}

我发现了一个类似于我的How to parse JSON Object Android Studio 的问题,但我无法将它应用到我的示例中。

【问题讨论】:

  • 你有什么问题?
  • 如何在第二个json中查找信息,因为它没有数组,只有NULL作为答案
  • 您要获取哪些信息? name键的值是你需要的吗?
  • 是的,我想访问它

标签: android json


【解决方案1】:

从 JSONObject 获取信息:

JSONObject aJsonObject = new JSONObject(aJsonResponse);
JSONArray aJsonArray = aJsonObject.getJSONArray("cliente");
for (int i = 0; i < aJsonArray.length(); i++) {
    aJsonObject = aJsonArray.getJSONObject(i);
String aId = aJsonObject .getString("id");
String aNome = aJsonObject .getString("nome");
}

【讨论】:

    【解决方案2】:

    尝试使用这个,你应该用来自服务器的响应替换 aJsonResponse

    JSONObject aJsonObject = new JSONObject(aJsonResponse);
    
    String aId = aJsonObject.getString("id");
    String aNome = aJsonObject.getString("name");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-02
      • 1970-01-01
      • 2019-10-03
      • 2016-07-19
      • 1970-01-01
      • 2017-12-27
      相关资源
      最近更新 更多