【发布时间】:2019-04-04 19:11:07
【问题描述】:
我试图理解为什么使用 getString 来解析 JSON 对象中的整数值
我查看了official documentation 它说:
获取字符串
public String getString(字符串名称)
如果存在则返回按名称映射的值,必要时强制它,如果不存在这样的映射,则抛出。
json文件为here
请注意 "id": 具有整数值
这是 MainActivity 中的代码
// looping through all Contacts
for (int i = 0; i < pokemons.length(); i++) {
//TODO: get the JSONObject and its three attributes
JSONObject c = pokemons.getJSONObject(i);
String name = c.getString("name");
>>> String id = c.getString("id"); <<<
String candy = c.getString("candy");
// tmp hash map for a single pokemon
HashMap<String, String> pokemon = new HashMap<>();
// add each child node to HashMap key => value
pokemon.put("name", name);
pokemon.put("id", id);
pokemon.put("candy", candy);
// adding a pokemon to our pokemon list
pokemonList.add(pokemon);
}
不应该是 getInt() 而不是 getString() 吗?因为正如您在 json 文件中看到的那样,id: 是 int 值的键! 我尝试用 getInt() 解析它并将其分配给一个 int 变量,它也可以工作!!
注意该代码来自 http 网络教程,它按预期工作,没有崩溃或错误,它不是我的代码。
【问题讨论】:
-
应该是
getInt(),使用getString()是什么意思。这看起来是你的代码。为什么不改呢? -
我会说它不一定是整数。我认为这些 ID 通常是不透明的,并且类型可以是字符串,例如,如果您想轻松适应类型的更改。想象一下,明天您迁移数据库并且 ID 变为 uuid,而不是简单的整数,它们现在是字符串。但我同意,既然这是您的代码,您可以更改它。
-
@Rohit5k2 @Fred 我已经添加了一条注释:它不是我的代码,它是一个教程代码,并且该应用程序与
String id = c.getString("id");一起工作