2017-06-20 60 views
-3

下面的代碼正在打印的散列值,而不是陣列如何散列映射值轉換爲字符串

JSONObject myjson1 = new JSONObject(expectedResult); 
       Iterator x = myjson1.keys(); 
       JSONArray jsonArray = new JSONArray(); 

       while (x.hasNext()){ 
        String key = (String) x.next(); 
        jsonArray.put(myjson1.get(key)); 
        System.out.println(x); 
       } 

輸出如下:

[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 

PS:轉換JSON來陣列(鍵:值)形式

+0

請參閱https://stackoverflow.com/questions/29140402/how-do-i-print-my-java-object-without-getting-sometype2f92e0f4 –

回答

0

不要使用(String)來代替使​​用的toString() 所以

String key = (String) x.next(); 
jsonArray.put(myjson1.get(key)); 
System.out.println(x.toString()); 

如果你想將其轉換爲字符串數組:

String[] result = jsonArray.values().toArray(new String[0]); 

你可以檢查此一: how to covert map values into string in Java

0

我建議你使用GSON庫來管理以.json文件。它更準確,更方便用戶,效果非常好。

順便說一句,你要求Java打印對象「x」(迭代器)。一個對象包含對自身內存分配的引用。 您必須要求軟件將其轉換爲可讀的格式,例如String is。 因此,嘗試在x調用後嘗試添加.toString()方法。

試着這樣做:

JSONObject myjson1 = new JSONObject(expectedResult); 
      Iterator x = myjson1.keys(); 
      JSONArray jsonArray = new JSONArray(); 

      while (x.hasNext()){ 
       String key = (String) x.next(); 
       jsonArray.put(myjson1.get(key)); 
       System.out.println(x.toString()); 
      } 

希望對大家有所幫助。

相關問題