2016-06-22 18 views
5

Sto provando a convertire HashSet<String> in JSONObject e quindi analizzare l'output JSON.Impossibile analizzare HashSet in stringa JSONObject

Ecco che cosa ho provato:

JSONObject json = new JSONObject(); 
json.put("set", new HashSet<>(Arrays.asList("a", "b"))); 
json.put("list", Arrays.asList("a", "b")); 
String jsonString = json.toJSONString(); 

System.out.println(jsonString); 

JSONParser parser = new JSONParser(); 
JSONObject afterParse = (JSONObject) parser.parse(jsonString); 
System.out.println(afterParse.toJSONString()); 

Ma mi sta dando questa uscita ed errore:

{"set":[b, a],"list":["a","b"]} 
Exception in thread "main" Unexpected character (b) at position 8. 

Qui, è possibile vedere sia a che b sono stringhe, nella lista sia sono racchiusi tra virgolette doppie ma nel set non lo è.

Sto usando org.json.simple v1.1.

+0

Hai provato a fare il vostro HashSet come HashSet ? Penso che non risolverà il problema, ma vale la pena di essere testato. –

+0

Ho provato a utilizzare HashSet ma l'output è lo stesso –

+1

Quando ho cambiato il pacchetto in 'org.json.JSONObject', lo stesso codice funziona. Non sono sicuro che possa essere un bug in org.json.simple. – Ravikumar

risposta

1

Penso che questo sia un problema con org.json.simple biblioteca.

ho usato org.json biblioteca e hanno a che fare alcune piccole modifiche nel codice qui sopra per lavorare:

JSONObject json = new JSONObject(); 
json.put("set", new HashSet<>(Arrays.asList("a", "b"))); 
json.put("list", Arrays.asList("a", "b")); 
String jsonString = json.toString(); 

System.out.println(jsonString); 

JSONObject afterParse = new JSONObject(jsonString); 
System.out.println(afterParse.toString()); 

L'uscita di questo codice è:

{"set":["a","b"],"list":["a","b"]} 
1

quando si converte un array di stringhe da elencare e quindi l'elenco in un Set, non è più String, ma una matrice di oggetti quindi new HashSet <> (Arrays.asList ("a", "b"))); dà "set": [b, a] (senza virgolette). E parser.parse (jsonString); funziona su Object non su array di oggetti.

provare a utilizzare un elenco invece di un insieme, come di seguito:

json.put("set", new Arraylist<>(new HashSet<>(Arrays.asList("a", "b")))); 
+0

so che se Converto set in lista funzionerà. ma volevo convertire HashSet in JSON direttamente –

+0

@Ashraful Islam, convertire Hashset che è una raccolta di JSON darà errore con il metodo json simple parse. L'utilizzo di un oggetto come Elenco farà l'affare. – mattymanme