2012-06-15 3 views
0

PHP를 통해 MySql DB로부터 정보를 얻고 있습니다. 정보는 다음 JSON 배열에 반환됩니다구문 분석 JSON 개별 문자열/int에 대한 문자열 배열

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를 사용하여 구축된다. 이제 나는 정보를 가지고 개별 문자열/ints에 대해 로컬 sqlite db에 넣으려는 구문을 분석하려고합니다. 여기

은 코드의 다음 줄을 사용할 수 있도록 내가 그 개별 문자열의 int로 정보를 반환 변환해야 어떻게
  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. 

질문

의 두 줄입니까? 어떤 자원에 대한 어떤 방향이라도 도움이 될 것입니다.

업데이트 I 코드의 두 개의 상기 라인 inbetween 다음 줄을 추가

는 출력 실제로 JSON 배열 아니다 널 포인터 예외

  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 객체입니다.

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(); 
} 

당신이 다음에는 getString int로 변환 할 필요가 있도록 "수량"과 "특급은"당신의 JSON 문자열입니다. 나는이 코드가 정확하다고 생각한다; 그것을 테스트하지 않았습니다.

+0

이것을 가져 주셔서 감사합니다. 반환되는 JSONObject가 userFunctions 클래스에서 정확합니다. 몇 가지 조사를 수행하고 편집 된 정보를 추가했습니다. 올바른 방향으로 나아가는 단계라고 생각하십니까? – KDEx