简体   繁体   中英

pass json_encode array to java through network

I am working on a coursework where I am trying to pass an array from php 'client' to java 'server'. I create an array in php, encode it with json_encode and receive it on the server site with StringVariable.readLine(). My problem:

The values of the php array are received as one value of the array in java. Have a look on the code and the output please.

PHP - as 'sender'

$array = array("foo", "bar", "hallo", "world");
$array2 = json_encode($array);
//var_dump($array);

$socket = fsockopen($server, $port, $eN, $eS);  

if ($socket)  
{  

fwrite($socket, $array2);

Java - as 'receiver'

BufferedReader in = new BufferedReader(new InputStreamReader(socket1.getInputStream())); 

 while ((in1 = in.readLine()) != null) 
                {  
                    String[] Decoder = {in1};
                    System.out.println(Arrays.asList(Decoder));

Results

[["foo","bar","hallo","world"]]

I ama generally looking for a solution where I pass array from PHP to JAVA through my lan. Any solution would be great.. I have tried also serialize() and what I receive is

[a:4:{i:0;s:3:"foo";i:1;s:3:"bar";i:2;s:5:"hallo";i:3;s:5:"world";}]

Help will be much apprecieted!!! THANK YOU!

You would use json_encode in PHP just like you are, and then a JSON decoder on the Java side; there's several (Jackson and Gson are both popular ones).

Here's a basic example using Gson :

String[] myStrings = new Gson().fromJson(in1, String[].class);

Better yet is not to use an array in Java, but a List:

Type type = new TypeToken<List<String>>(){}.getType();
List<String> myStrings = new Gson().fromJson(in1, type);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM