本文介绍了将数组 php 转换为 java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个包含 java 文件和 php 文件的应用程序.java 文件调用 php 文件,这些文件在 ddbb 中执行查询并将结果作为数组 php 返回,但将其打印在屏幕上.我在java中把它当作一个字符串,我必须把它转换成数组或集合,但我不知道该怎么做.

I am developing an app that has java files and php files. The java files call to the php files, these execute queries in the ddbb and return the result as an array php, but printing it in the screen. I take this in java like an string, and I have to convert it to and array or collection, but I have no idea how to do it.

php 打印结果的一个例子是:

An example of the result that php prints is:

Array
(
[0] => Array
    (
        [id] => 1
        [0] => 1
        [name] => pepe
        [1] => pepe
    )

[1] => Array
    (
        [id] => 2
        [0] => 2
        [name] => antoñito
        [1] => antoñito
    )

[2] => Array
    (
        [id] => 3
        [0] => 3
        [name] => loló
        [1] => loló
    )

[3] => Array
    (
        [id] => 4
        [0] => 4
        [name] => ñoño
        [1] => ñoño
    )

[4] => Array
    (
        [id] => 5
        [0] => 5
        [name] => Antoñito
        [1] => Antoñito
    )

[5] => Array
    (
        [id] => 7
        [0] => 7
        [name] => José
        [1] => José
    )

)

如果我使用 json_encode($the_array) 这是结果:

If I use json_encode($the_array) this is the result:

[{"id":"1","0":"1","name":"pepe","1":"pepe"},    {"id":"2","0":"2","name":"anto\u00f1ito","1":"anto\u00f1ito"},{"id":"3","0":"3","name":"lol\u00f3","1":"lol\u00f3"},{"id":"4","0":"4","name":"\u00f1o\u00f1o","1":"\u00f1o\u00f1o"},{"id":"5","0":"5","name":"Anto\u00f1ito","1":"Anto\u00f1ito"},{"id":"7","0":"7","name":"Jos\u00e9","1":"Jos\u00e9"}]

谢谢大家

推荐答案

您应该为您的数据选择一种序列化方法.例如XML、协议缓冲区或 JSON.

You should select a serialization method for your data. For e.g. XML, Protocol Buffers or JSON.

我个人建议您使用 JSON,因为它是轻量级的,即使对于人类也易于阅读,并且有多种可供两种语言使用的库.

I personally recommend you to use JSON because it's lightweight, easy to read even for humans and there are broad selection of libraries available for both languages.

$encoded = json_encode($data);

使用 Jackson 在 Java 端解码

final ObjectMapper objectMapper = new ObjectMapper();
// the better way is to create a custom class with the correct format
final Map<?, ?> decoded = objectMapper.readValue(encoded, Map.class);

这篇关于将数组 php 转换为 java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 01:55