2010-06-08 211 views
4

這是一個奇怪的問題。這裏是我的代碼將Java字符串轉換爲數組

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

executeUrl返回字符串對象無論由reply.php文件返回什麼。 現在出現這個問題。在reply.php中,我返回一個PHP數組,並且答覆是一個String。

當我做

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

我得到

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

但答覆仍然是一個字符串。我如何將其轉換爲字符串數組或數組。

回答

2

沒有什麼奇怪它是在所有。你已經宣佈String reply,所以當然這是一個字符串。將String拆分爲String[]的標準方法是使用String.split,但我會認真考慮更改回復字符串的格式,而不是試圖找出當前格式的正則表達式,因爲它不是那麼友好,因爲它是。

1

您可能需要更改reply.php的行爲,並返回一個字符串而不是數組。

也許像

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

我需要在Java端陣列。我如何獲得? – Bruce 2010-06-08 14:48:48

+0

忘記了,就像thetaiko說JSON是你需要的:) – 2010-06-08 14:56:00

8

您可能想嘗試在reply.php中返回JSON對象,然後使用JSON庫將其導入到Java中。

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

reply.php:

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

在你的Java代碼:

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

JSON的+1!兩種語言都支持庫中的標準格式! – polygenelubricants 2010-06-08 14:52:55

1

解析與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]