2012-06-15 215 views
0

我通过PHP从MySql DB获取信息。这些信息将返回以下JSON数组中:为单个字符串/整数解析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

这实际上不是一个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(); 
} 

“数量” 和 “EXP” 在你的JSON字符串,所以你需要给GetString然后将其转换为int。我认为这段代码是正确的;还没有测试过它。

+0

感谢您提出这个问题,您在userFunctions类中正确地返回了正在返回的JSONObject。我做了一些调查并添加了编辑后的信息,你认为这是朝正确方向迈出的一步吗? – KDEx