In web development, PHP and Java are both very common programming languages. In different application scenarios, both languages have considerable advantages. In some projects, we may need to convert PHP arrays into object arrays in Java. This is a very common requirement. Below, we will learn how to achieve this requirement.
First, we need to convert PHP array into JSON format string:
$array = array( 'name' => 'John', 'age' => 20, 'gender' => 'male' ); $json_string = json_encode($array); echo $json_string;
Run the above Code, the output is as follows:
{"name":"John","age":20,"gender":"male"}
Then, we need to parse the JSON string in Java and convert the JSON string into a Java object :
import com.google.gson.Gson; class User { String name; int age; String gender; public User(String name, int age, String gender) { this.name = name; this.age = age; this.gender = gender; } } public class Main { public static void main(String[] args) { String json_string = "{\"name\":\"John\",\"age\":20,\"gender\":\"male\"}"; Gson gson = new Gson(); User user = gson.fromJson(json_string, User.class); System.out.println(user.name + " " + user.age + " " + user.gender); } }
Run the above code, the output is as follows:
John 20 male
Next, we convert the PHP array into Java object array:
$array = array( array( 'name' => 'John', 'age' => 20, 'gender' => 'male' ), array( 'name' => 'Tom', 'age' => 21, 'gender' => 'male' ), array( 'name' => 'Lucy', 'age' => 19, 'gender' => 'female' ) ); $json_string = json_encode($array); echo $json_string;
Run the above code, the output is as follows:
[{"name":"John","age":20,"gender":"male"},{"name":"Tom","age":21,"gender":"male"},{"name":"Lucy","age":19,"gender":"female"}]
We need to use the array in Java to receive the objects in the JSON string:
import com.google.gson.Gson; class User { String name; int age; String gender; public User(String name, int age, String gender) { this.name = name; this.age = age; this.gender = gender; } } public class Main { public static void main(String[] args) { String json_string = "[{\"name\":\"John\",\"age\":20,\"gender\":\"male\"},{\"name\":\"Tom\",\"age\":21,\"gender\":\"male\"},{\"name\":\"Lucy\",\"age\":19,\"gender\":\"female\"}]"; Gson gson = new Gson(); User[] users = gson.fromJson(json_string, User[].class); for (User user : users) { System.out.println(user.name + " " + user.age + " " + user.gender); } } }
Run the above The code output is as follows:
John 20 male Tom 21 male Lucy 19 female
So far, we have successfully converted a PHP array into a Java object array. In this way, we can flexibly use PHP and Java in different projects to achieve better web applications.
The above is the detailed content of Let's talk about how to convert a php array into a java object array. For more information, please follow other related articles on the PHP Chinese website!