JSON is an XML-like common data Interchange Format, which is more efficient than XML. It is more advantageous for the network to transmit data. Here, some use the Gosn class to process JSON data. Gson is faster than traditional JSON processing and gson open source. If you are interested, you can also learn about Ali development of the Fastgson, the speed is very fast.
Using GOSN to process JSON is straightforward. First we first create a JavaBean class
(1) Create User.java
Public classUser { PublicUser (String name,intAge ) { This. Name =name; This. Age =Age ; } PrivateString name; Private intAge ; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; }}View Code
(2) Parse the following JSON format data:
String Jsondata = "[{\" name\ ": \" john\ ", \" age\ ": 18},{\" name\ ": \" jason\ ", \" age\ ": 16}]";//Resolving TypesType ListType =NewTypetoken<linkedlist<user>>() {}.gettype ();//Create Gson instance, Gson Gson = new Gson ();Gson Gson =gsonfactory.getgsoninstance ();//parsing JSON datalinkedlist<user> users =Gson.fromjson (Jsondata, listtype);//Iterative Output for(Iterator Iterator =users.iterator (); Iterator.hasnext ();) {User User=(User) iterator.next (); System.out.println (User.getname ()); System.out.println (User.getage ()); }
(3) JavaBean using Gson to generate JSON data
list<user> userlist=new linkedlist<user>();
User user1 =new User ("Zhang San", 20 User user2 =new User ("John", 45 // create Gson instance = Gson (); // Generate JSON formatted data String jsondata =gson.tojson (UserList) System.out.println (jsondata); // The output is: [{"Name": "Zhang San", "Age": 20},{"name": "John", "Age": "}]
Here the main use of Gson two methods:
1. Methods for parsing JSON Fromjson
2. How to generate JSON ToJson