2013-03-29 12 views
13

Ho analizzato alcuni dati JSON e funziona bene fino a quando lo memorizzo in variabili String.Come analizzare JSON in un int?

Il mio problema è che ho bisogno dell'ID in un varibable int e non in String. ho provato a fare un cast int id = (int) jsonObj.get("");

Ma dà un messaggio di errore che non riesco a convertire un oggetto in un int. così ho cercato di convertire utilizzando:

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

Ma anche che non funziona. Che c'è. Come funziona JSON con int? Le mie stringhe stanno funzionando bene solo quando provo a renderle come int ho problemi.

Ecco il mio codice:

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


     } 

    } 

risposta

13

È possibile utilizzare parseInt:

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

o meglio e più direttamente il metodo getInt:

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

getInt() non funziona con una semplice JSON – Josef

+0

Cosa vuoi dire? Cosa c'è esattamente nella stringa 'id'? –

+0

int id = Integer.parseInt (jsonObj.get ("id")); Questa eclissi vuole aggiungere un cast a String. – Josef

9

Dipende dal tipo di proprietà che stai analizzando.

Se la proprietà JSON è un numero (ad esempio, 5) si può lanciare a Long direttamente, in modo che si possa fare:

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

Dopo avere ottenuto il tempo, si potrebbe lanciare ancora una volta a int, con conseguente:

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

Se la proprietà jSON è un numero con le virgolette (ad esempio "5"), si è considerata una stringa, e avete bisogno di fare qualcosa di simile a Integer.parseInt() o Long.parseLong();

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

L'unico problema è che, se a volte riceve id è una stringa o come numero (non puoi prevedere il formato del cliente o lo fa in modo intercambiabile), si potrebbe ottenere un'eccezione, soprattutto se si utilizza parseInt/Long su un oggetto json null.

Se non si utilizza Java Generics, il modo migliore per affrontare queste eccezioni di runtime che uso è:

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

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

Si potrebbe anche rimuovere quel primo se e aggiungere l'eccezione alla cattura. Spero che questo aiuti.

1

Non hanno funzionato per me. Ho fatto questo e ha funzionato:

Per codificare come JSON:

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

per decodificare:

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

è molto semplice.

Esempio JSON:

{ 
    "value":1 
} 


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

Io uso una combinazione di json.get() e instanceof per leggere i valori che potrebbero essere sia interi o stringhe interi.

Questi tre casi di test illustrano:

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 
}