简体   繁体   English

将Java字符串转换为数组

[英]Convert Java String to Array

This is a weird problem. 这是一个奇怪的问题。 Here is my code 这是我的代码

 String reply = listen.executeUrl("http://localhost:8080/JavaBridge/reply.php); 

executeUrl returns as String object whatever is returned by the reply.php file. executeUrl作为String对象返回reply.php文件返回的任何内容。 Now comes the problem. 现在出现了问题。 In reply.php I am returning an PHP array and reply is a String. 在reply.php我返回一个PHP数组,回复是一个字符串。

When I do 当我做

System.out.println("Reply = "+reply);  

I get 我明白了

Reply =       array(2) {  [0]=>  string(14) "Dushyant Arora"  [1]=>  string(19
) "@dushyantarora13 hi"}

But reply is still a String. 但回复仍然是一个字符串。 How do I convert it into a String array or an Array. 如何将其转换为String数组或Array。

You might want to try returning a JSON object in reply.php and then importing that into Java using the JSON libraries. 您可能希望尝试在reply.php中返回JSON对象,然后使用JSON库将其导入Java。

http://www.json.org/java/ http://www.json.org/java/

reply.php: reply.php:

<?
...
echo json_encode($yourArray);

In your Java code: 在您的Java代码中:

...
JSONArray reply = new JSONArray(listen.executeUrl("http://localhost:8080/JavaBridge/reply.php"));

There's nothing weird about it at all. 根本没什么奇怪的。 You have declared String reply , so of course it's a string. 你已经声明了String reply ,所以当然它是一个字符串。 The standard way of splitting a String into a String[] is to use String.split , but I'd seriously consider changing the format of the reply string rather than trying to figure out the regex for the current format, because it's not all that friendly as it is. String拆分为String[]的标准方法是使用String.split ,但我会认真考虑更改回复字符串的格式,而不是试图找出当前格式的正则表达式,因为它不是全部这是友好的。

You may want to change the behaviour of reply.php, and return a string instead of an array. 您可能希望更改reply.php的行为,并返回字符串而不是数组。

Maybe something like 也许是这样的

// ...
return implode(" ", $your_reply_array) ;

Parsing a PHP array with Java is not the cleanest solution, but I can never resist a good regex problem. 使用Java解析PHP数组并不是最干净的解决方案,但我永远无法抵抗正确的正则表达式问题。

public static void main(String[] args) {
    Pattern p = Pattern.compile("\\[\\d+\\]=>  string\\(\\d+\\) \"([^\"]*)\"");
    String input = "      array(2) {  [0]=>  string(14) \"Dushyant Arora\"  [1]=>  string(19" +
            ") \"@dushyantarora13 hi\"}";
    ArrayList<String> list = new ArrayList<String>();
    Matcher m = p.matcher(input);
    while (m.find()) {
        list.add(m.group(1));
    }
    System.out.println(list);
}

[Dushyant Arora, @dushyantarora13 hi]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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