【问题标题】:Display nested data from JSON in textview android在textview android中显示来自JSON的嵌套数据
【发布时间】:2026-01-07 22:35:01
【问题描述】:

我认为这个问题是微不足道的,但我在编程方面并不先进。我在向 TextView 显示 Json 数据时遇到问题 我的 Json 文件是这样的

{
    "person":{
        "firstName":"John",
        "lastName":"Jankow",
        "nick":"Jayjay"
        }
...
}

当我使用时,来自 Json 的其他数据(例如地址、ID 等)显示没有问题

 ((TextView) findViewById(R.id.person)).setText("Person: " + json.optString("person"));

我得到字符串“人”:{ "firstName":"约翰", "lastName":"Jankow", “尼克”:“杰杰” }" 我尝试使用 ((TextView) findViewById(R.id.person)).setText("Person: " + json.optString("firstName") + json.optString("lastName"));

但结果是空的TextView。 问题 ==> 有什么方法可以处理这些数据并像子字符串或类似的东西正确显示?

【问题讨论】:

  • 在你的问题中,变量 json 是否指向 json 字符串?

标签: android json parsing textview


【解决方案1】:

这样做

JSONObject person = json.getJSONObject("person");
((TextView) findViewById(R.id.person)).setText("Person: " + person.getString("firstName") + person.getString("lastName"));

【讨论】:

    【解决方案2】:

    不完全确定这是否有帮助,但看看这个。

    JSONObject person = jsonObj.getJSONObject("person");
    String firstName = person.getString("firstName");
    String lastName = person.getString("lastName");
    

    以一种很棒的方式使用字符串。

    textView.setText(firstName);
    

    【讨论】:

    • 如果对您有帮助,请考虑接受答案。和平。