Gson的简单使用

package test;



import com.google.gson.Gson;

import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;



/**

 * @author 

 */

public class GsonTest {

    

    public static void main(String args[]){

        //parseJSONObject();

        

        //parseJSONArray();

        

       // createJSONObject();

        

       // createJSONArray();

        

    }

    

    /**

     * 解析JSON 对象

     */

    public static void parseJSONObject(){

        String json = "{'name':'张三', 'age':25}";

        Gson gson = new Gson();

        User user = gson.fromJson(json, User.class);

        System.out.println(user);

    }

    

    /**

     * 生成JSON对象

     */

    public static void createJSONObject(){

        Gson gson = new Gson();

        User user = new User();

        user.name = "测试";

        user.age = 100;

        String json = gson.toJson(user);

        System.out.println(json);

    }

    

    /**

     * 解析JOSN数组

     */

    public static void parseJSONArray(){

        String json = "[{'name':'张三', 'age':25},{'name':'李四', 'age':25}]";

        Gson gson = new Gson();

        List<User> list = gson.fromJson(json, new TypeToken<List<User>>(){}.getType());

        Iterator<User> iter = list.iterator();

        while(iter.hasNext()){

            User user = iter.next();

            System.out.println(user);

        }

    }

    

    /**

     * 生成JSON数组

     */

    public static void createJSONArray(){

        Gson gson = new Gson();

        List<User> list = new ArrayList<>();

        User user = new User();

        user.name = "张三";

        user.age = 100;

        list.add(user);

        user = new User();

        user.name = "李四";

        user.age = 200;

        list.add(user);

        

        String json = gson.toJson(list, new TypeToken<List<User>>(){}.getType());

        System.out.println(json);

    }

    

    final static class User{

        public String name;

        public int age;

        

        @Override

        public String toString(){

            return "Nmae:"+name+"\tAge:"+age;

        }

    }

}

 

你可能感兴趣的:(gson)