Suppose we have obtained a Java object on the server side, and now we are considering how to convert this Java object into a string that complies with the JSON syntax. Of course, we can write a set of algorithms to implement this conversion, but it is troublesome, especially when the object has many attributes or the attribute Nesting is deep, it is more troublesome.
In practice, we can use a ready-made tool to implement this conversion process:
User. Java:
public class User {private String name;private int age;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public User() {super();}public User(String name, int age) {super();this.name = name;this.age = age;}}
Test. Java:
Public class test {public static void main (string [] ARGs) {// test1 (); Test2 (); // test3 ();} // convert a Java object into a JSON-compliant string public static void test1 () {user = new user ("Tom", 20); jsonobject JSON = jsonobject. fromobject (User); string json_str = JSON. tostring (); system. out. println (json_str);} // convert a Java array into a JSON-compliant string public static void Test2 () {user user1 = new user ("Tom", 20 ); user user2 = new user ("green", 25); User [] users = {user1, user2}; jsonarray JSON = jsonarray. fromobject (users); string json_str = JSON. tostring (); system. out. println (json_str);} // converts a Java set into a JSON-compliant string public static void test3 () {user user1 = new user ("Tom", 20 ); user user2 = new user ("green", 25); User user3 = new user ("Smith", 30); List <user> Users = new arraylist <user> (); users. add (user1); users. add (user2); users. add (user3); jsonarray JSON = jsonarray. fromobject (users); string json_str = JSON. tostring (); system. out. println (json_str );}}
All you need to do is import the corresponding jar package, where the JSON package is the core package, and the rest is the dependent package. Jar packages can be downloaded from my resources for free.
UseJsonobject(Convert Java objects) andJsonarray(Convert the Java object array or Java set)Fromobject ()Method. After obtaining the JSON object, callTostring ()Method to obtain the string that meets the JSON syntax.