Convert Java string to array

This is a strange problem. Here is my code

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

executeUrl returns as a String object everything that is returned by the reply.php file. Now the problem. In reply.php, I return a PHP array, and the answer is a string.

When i do

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

I get

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

But the answer is still a string. How to convert it to a String array or an array.

+4
source share
4 answers

There is nothing strange about this. You declared String reply , so of course this is a string. The standard way to split a String into a String[] is to use String.split , but I would seriously think about changing the format of the response string, rather than trying to figure out the regular expression for the current format, because it's not so friendly.

+2
source

You might want to try returning the JSON object to the answer.php file and then import it into Java using the JSON libraries.

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

reply.php:

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

In Java code:

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

You might want to change the behavior of answer.php and return a string instead of an array.

Maybe something like

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

Parsing a PHP array using Java is not the cleanest solution, but I can never resist a good regex problem.

 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]

+1
source

Source: https://habr.com/ru/post/1312215/


All Articles