2013-03-29 69 views
13

我已經解析了一些JSON數據,它的工作正常,只要我將它存儲在字符串變量中。如何解析JSON到一個int?

我的問題是我需要的ID在一個int varibable而不是字符串。 我試圖做一個演員int id = (int) jsonObj.get("");

但它給出了一個錯誤消息,我不能將一個對象轉換爲int。 所以我試圖用轉換:

String id = (String) jsonObj.get("id"); 
int value = Integer.parseInt(id); 

但也未工作。哪裏不對。 JSON如何與int一起工作? 我的字符串工作得很好,只有當我嘗試使它們成爲一個int時出現問題。

這裏是我的代碼:

public void parseJsonData() throws ParseException { 

     JSONParser parser = new JSONParser(); 
     Object obj = parser.parse(jsonData); 
     JSONObject topObject = (JSONObject) obj; 
     JSONObject locationList = (JSONObject) topObject.get("LocationList"); 
     JSONArray array = (JSONArray) locationList.get("StopLocation"); 
     Iterator<JSONObject> iterator = array.iterator(); 

     while (iterator.hasNext()) { 

      JSONObject jsonObj = (JSONObject) iterator.next(); 
      String name =(String) jsonObj.get("name"); 
      String id = (String) jsonObj.get("id"); 
      Planner.getPlanner().setLocationName(name); 
      Planner.getPlanner().setArrayID(id); 


     } 

    } 

回答

13

您可以使用parseInt

int id = Integer.parseInt(jsonObj.get("id")); 

或更好,更直接的getInt方法:

int id = jsonObj.getInt("id"); 
+3

getInt()不與簡單的JSON – Josef

+0

工作你是什麼意思?你的'id'字符串究竟是什麼? –

+0

int id = Integer.parseInt(jsonObj.get(「id」));這一次日食想要添加一個強制轉換爲字符串。 – Josef

9

這取決於物業類型你正在解析。

如果JSON屬性是一個數字(例如5),您可以轉換爲長期直接,所以你可以這樣做:

(long) jsonObj.get("id") // with id = 5, cast `5` to long 

越來越長,你可以施放後再次爲int,導致:

(int) (long) jsonObj.get("id") 

如果JSON屬性加上引號(例如,「5」)的數字,是被認爲是一個字符串,你需要做類似的Integer.parseInt()或的Long.parseLong()的東西;

Integer.parseInt(jsonObj.get("id")) // with id = "5", convert "5" to Long 

唯一的問題是,如果你有時會收到ID是一個字符串或一個數字(你不能預知客戶的格式或它確實是可以互換),你可能會得到一個異常,特別是如果你使用parseInt函數/龍在一個空json對象上。

如果不使用Java泛型,對付我使用這些運行時異常的最好辦法是:

if(jsonObj.get("id") == null) { 
    // do something here 
} 

int id; 
try{ 
    id = Integer.parseInt(jsonObj.get("id").toString()); 
} catch(NumberFormatException e) { 
    // handle here 
} 

你也可以刪除第一如果和異常增加漁獲物。 希望這有助於。

1

非他們爲我工作。 我這樣做,它的工作:

要編碼爲JSON:

JSONObject obj = new JSONObject(); 
obj.put("productId", 100); 

爲了解碼:

long temp = (Long) obj.get("productId"); 
4

它非常簡單。

例JSON:

{ 
    "value":1 
} 


int z = jsonObject.getInt("value"); 
0

我使用json.get()和的instanceof的組合中,可能是任一整數或整數字符串值讀取。

這三個測試案例說明:

int val; 
Object obj; 
JSONObject json = new JSONObject(); 
json.put("number", 1); 
json.put("string", "10"); 
json.put("other", "tree"); 

obj = json.get("number"); 
val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj); 
System.out.println(val); 

obj = json.get("string"); 
val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj); 
System.out.println(val); 

try { 
    obj = json.get("other"); 
    val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj); 
} catch (Exception e) { 
    // throws exception 
}