[英]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'. 我正在尝试将php'client'的数组传递给java'server'的课程。 I create an array in php, encode it with json_encode and receive it on the server site with StringVariable.readLine(). 我在php中创建一个数组,使用json_encode对其进行编码,并使用StringVariable.readLine()在服务器站点上将其接收。 My problem: 我的问题:
The values of the php array are received as one value of the array in java. php数组的值作为java中数组的一个值接收。 Have a look on the code and the output please. 请看一下代码和输出。
PHP - as 'sender' PHP-作为“发送者”
$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' Java-作为“接收者”
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"]] [[“ foo”,“ bar”,“你好”,“世界”]]
I ama generally looking for a solution where I pass array from PHP to JAVA through my lan. 我通常会在寻找一种解决方案,通过局域网将PHP数组从PHP传递到JAVA。 Any solution would be great.. I have tried also serialize() and what I receive is 任何解决方案都很好。我也尝试了serialize() ,得到的是
[a:4:{i:0;s:3:"foo";i:1;s:3:"bar";i:2;s:5:"hallo";i:3;s:5:"world";}] [a:4:{i:0; s:3:“ foo”; i:1; s:3:“ bar”; i:2; s:5:“ hallo”; i:3; s:5: “世界”;}]
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; 您将像在PHP中一样使用json_encode
,然后在Java端使用JSON解码器; there's several (Jackson and Gson are both popular ones). 有几个(杰克逊和格森都很受欢迎)。
Here's a basic example using Gson : 这是使用Gson的基本示例:
String[] myStrings = new Gson().fromJson(in1, String[].class);
Better yet is not to use an array in Java, but a List: 更好的是不要在Java中使用数组,而要使用List:
Type type = new TypeToken<List<String>>(){}.getType();
List<String> myStrings = new Gson().fromJson(in1, type);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.