2012-06-15 212 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