2017-06-20 61 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()); 
      } 

希望对大家有所帮助。

相关问题