For example, for a user object, I want a framework that can be directly converted to {ID: 1001, name = 'zhangsan'}. Currently, Google's gson component is good, it also supports generic JDK 5.
Address: http://code.google.com/p/google-gson/
User user class:
Public class user {
@ Expose
Private long ID;
@ Expose
Private string name;
Public long GETID (){
Return ID;
}
Public void setid (long ID ){
This. ID = ID;
}
Public String getname (){
Return name;
}
Public void setname (string name ){
This. Name = Name;
}
}
// Test the JavaBean conversion.
Public class test {
Public static void main (string [] ARGs ){
User user = new user ();
User. setid (1001l );
User. setname ("Zhang San ");
Gsonbuilder builder = new gsonbuilder ();
// Do not convert fields without the @ expose Annotation
Builder. excludefieldswithoutexposeannotation ();
Gson = builder. Create ();
String suser = gson. tojson (User );
System. Out. println (suser );
// {"ID": 1001, "name": "Zhang San "}
// Convert a JSON string to a JavaBean
User user2 = gson. fromjson (suser, user. Class );
System. Out. println (user2.getid () + "," + user2.getname ());
// 1001, Zhang San
}
}
// Test the conversion of hashmap
Public class maptest {
Public static void main (string [] ARGs ){
User user1 = new user ();
User1.setid (1001l );
User1.setname ("James ");
User user2 = new user ();
User2.setid (1002l );
User2.setname ("Li Si ");
Map usermap = new hashmap ();
Usermap. Put ("user1", user1 );
Usermap. Put ("user2", user2 );
Gsonbuilder builder = new gsonbuilder ();
// Do not convert fields without the @ expose Annotation
Builder. excludefieldswithoutexposeannotation ();
Gson = builder. Create ();
String susermap = gson. tojson (user, new typetoken> () {}. GetType ());
System. Out. println (susermap );
// {"User1": {"ID": 1001, "name": "zhangsan"}, "user2": {"ID": 1002, "name ": "Li Si "}}
// Convert the JSON string to hashmap
Map usermap2 = (MAP) gson. fromjson (suser, new typetoken> () {}. GetType ());
System. Out. println (usermap2.get ("user1"). getname ());
// John
}
}
Of course, gson's JSON parsing settings are not limited to this, as well as version annotations, annotations for changing field names, and so on.
The above URL contains specific development documents and detailed examples.
Today, gson has been adopted by many companies, making it convenient and convenient. Google is quite powerful. </String,>