1

There are Arrays in Arrays:

Array 
(
 [0] => Array (  [0] => v1  [1] => v2  [2] => v3 )
 [1] => Array (  [0] => v1  [1] => v2  [3] => v3 )
 [2] => Array (  [0] => v1  [1] => v2  [10] => v3 )
 [4] => Array (  [0] => v1  [1] => v2  [3] => v3 )
)

After json_encode on andorid I get the following:

{
 «0»: [ «v1», «v2», «v3» ],
 «1»: { «0»:«v1», «1»:«v2», «3»:«v3», },
 «2»: { «0»:«v1», «1»:«v2», «10»:«v3» },
 «4»: { «0»:«v1», «1»:«v2», «3»:«v2» }
}

JSONArray jList = jb.getJSONArray(response); //exception is not array

Is there a good way to parse this as Array[Array[]] on Android?

3
  • can you show us the whole chunk of PHP code that starts with the array as input and ends with the string containing «/» characters. There's something really odd going on there, but I can't see it from what you've posted. Commented Feb 14, 2013 at 14:05
  • I don`t have access to php script. Author show me debug print of array before and after json_encode. php.net/manual/en/function.json-encode.php Sequential array sample Commented Feb 14, 2013 at 14:30
  • well, php's json_decode won't put those «/» characters in there, so I'm wondering where they've come from. They're obviously not standard json. Standard json should have " characters for the quotes. Commented Feb 14, 2013 at 14:37

1 Answer 1

0

This happens because you have non-contiguous indices. If you "renumber" the array with

$a = array_values($a);

you will have

Array 
(
    [0] => Array (  [0] => v1  [1] => v2  [2] => v3 )
    [1] => Array (  [0] => v1  [1] => v2  [3] => v3 )
    [2] => Array (  [0] => v1  [1] => v2  [10] => v3 )
    [3] => Array (  [0] => v1  [1] => v2  [3] => v3 )
)

and as a result json_encode will create

[ ["v1", "v2", "v3"], { "0": "v1", ...}, ... ]

If you want to have inner arrays too, you must ensure that the inner arrays have contiguous indices as well.

If you can't change the PHP code, the only way is to parse this as a JSON object and iterate over the properties using keys() and pick the values individually.

3
  • I can only parse result on android. php script can`t change. Commented Feb 14, 2013 at 14:39
  • @AlexandrSulimov But your colleague can fix his code. If not, you must parse as an object, please see updated answer. Commented Feb 14, 2013 at 14:51
  • There is no reason to change php script. This is default way in php json_encode on sequential array. I seek way for small coding in android. Top level array is JSSONObject second level JSONArray [0], JSSONObject [1], JSSONObject [2], JSSONObject [4]. But if chage fourth element from [4] to [3] json_encode optimize and top level Array be a JSONArray Commented Feb 14, 2013 at 14:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.