简体   繁体   English

getString(“ K”)是否能够从json对象提取int值?

[英]Is getString(“K”) able to extract int value from json Object?

I am trying to understand why getString is used to parse integer value from JSON Object 我试图理解为什么使用getString来解析JSON对象中的整数值

i looked in the official documentation and it says: 我查看了官方文档 ,上面写着:

getString getString

public String getString (String name) public String getString(字符串名称)

Returns the value mapped by name if it exists, coercing it if necessary, or throws if no such mapping exists. 返回按名称映射的值(如果存在),如果需要则强制转换,如果不存在则抛出。

The json file is here json文件在这里

please note that "id" : has integer value 请注意“ id” :具有整数值

and here is the code in MainActivity 这是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);
}

Shouldn't it be getInt() instead of getString() ? 应该不是getInt()而不是getString()吗? because as you see in the json file id: is a key to an int value ! 因为正如您在json文件中看到的那样, id:是一个int值的键 i tried parsing it with getInt() and assign it to an int variable and it worked too!! 我试图用getInt()解析它,并将其分配给一个int变量,它也起作用了!

NOTE that code is from a tuturial on http networking and it is working as intended without crash or error and it is not my code. 请注意 ,该代码来自http网络上的教程,它可以按预期工作,不会崩溃或出错,并且它不是我的代码。

It should be getInt(String name) and you should change it. 它应该是getInt(String name)并且应该更改它。 Or you can use optInt(String name, int fallback) also. 或者,您也可以使用optInt(String name, int fallback) Documentation is here 文档在这里

Also, if you change it then you will have to change 另外,如果您更改它,那么您将不得不更改

pokemon.put("id", id);

to either

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

because your HashMap expects a string in the value field. 因为您的HashMap在value字段中需要一个字符串。

you can use 您可以使用

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

JsonObject has method with name getInt() JsonObject具有名称为getInt()的方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM