【问题标题】:Is getString("K") able to extract int value from json Object?getString("K") 是否能够从 json 对象中提取 int 值?
【发布时间】: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"); 一起工作

标签: java android json


【解决方案1】:

它应该是getInt(String name),你应该改变它。或者你也可以使用optInt(String name, int fallback)。文档是here

另外,如果你改变它,那么你将不得不改变

pokemon.put("id", id);

到任一

pokemon.put("id", id + "");pokemon.put("id", String.valueOf(id));

因为您的 HashMap 在值字段中需要一个字符串。

【讨论】:

    【解决方案2】:

    你可以使用

    int id = c.getInt("id"); 
    

    JsonObject 有方法名 getInt()

    【讨论】:

    • 您真的希望通过分配将int 放入string 吗?我更担心谁赞成这个。
    • @Rohit5k2 我的错,我在复制时错过了更改它,感谢您的指点。如果您提出修改建议会更好
    猜你喜欢
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 2014-04-13
    • 1970-01-01
    相关资源
    最近更新 更多