-3

The following code is printing hash values instead of Array

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

The output is as follows:

java.util.HashMap$KeyIterator@42a0b130
java.util.HashMap$KeyIterator@3c2a5fb9
java.util.HashMap$KeyIterator@6e68bc46
java.util.HashMap$KeyIterator@3223cb64
java.util.HashMap$KeyIterator@256c426b

PS: Converting Json to Array (key : value) form

Fraction
  • 3
  • 2
  • 10

2 Answers2

0

Do not use (String) instead use toString() So

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

And if you want to convert it to string array:

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

And you can check this one: how to covert map values into string in Java

0

I suggest you to use Gson library to manage .json files. It's more accurate, it's more user-friendly and it works very well.

By the way you're asking Java to print the object "x" (Iterator). An object contains the reference to the memory allocation of itself. You have to ask your software to convert it in a human-readable format, such as String is. So try to add .toString() method after x invocation.

Try to do something like:

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

I hope to be helpful.

Gozus19
  • 165
  • 19