解析单个字符串/整数的JSON字符串数组

时间:2012-06-15 13:47:06

标签: android arrays json string int

我通过PHP从MySql DB获取信息。信息在以下JSON数组中返回:

06-15 15:20:17.400: E/JSON(9865): {"tag":"get_game_state","success":1,"error":0,"GameState":{"monster":"Troll","qty":"1","exp":"0"}}

解析json并使用StringBuilder构建字符串。现在我已经返回了信息,我想解析它包含的各个字符串/整数,以便将它们放在本地sqlite数据库中。

以下是有问题的两行

            userFunctions.getServerGameState(email, monster, qty, exp); //this line gets the JSON array and the above information is returned
            db.saveLocalGameSate(monster, qty, exp); //this line should take that information take String monster int exp and int qty and put them in the local db. 

我应该如何将返回的信息转换为单个字符串和整数,以便它们可以在下一行代码中使用?对某些资源的任何指导都会非常有帮助。

更新

我在上面两行代码之间添加了以下几行,输出是一个空指针异常

            try {
            JSONArray arr = new JSONArray(GameState);
            JSONObject jObj = arr.getJSONObject(0);
            String virtumon = jObj.getString("monster");
            Integer qty = jObj.getInt("qty");
            Integer exp = jObj.getInt("exp");

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

1 个答案:

答案 0 :(得分:1)

那实际上不是JSON数组;它是一个JSON对象(花括号的原因而不是方括号。)

JSONObject()的一个构造函数接受包含JSON的字符串,并将解析它并创建一个JSON对象。我无法发布链接,但请参阅d.android.com上的JSONObject文档。

一旦有了JSONObject,就可以使用getString(),getInt(),optString()和optInt()来提取所需的数据。


假设'responseString'是完整的响应字符串:

try {
  JSONObject responseObj = new JSONObject(responseString);
  JSONObject gameStateObj = responseObj.getJSONObject("GameState");
  String monsterType = gameStateObj.getString("monster");
  int qty = Integer.parseInt(gameStateObj.getString("qty"));
  int exp = Integer.parseInt(gameStateObj.getString("exp");
} catch (JSONException ex) {
  e.printStackTrace();
}

“qty”和“exp”是json中的字符串,因此您需要getString然后转换为int。我认为这段代码是正确的;尚未测试过。