Simple usage example of GSON

 

 

 

package test.zhizhi;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 *
 * @ClassName Item
 * @author kanpiaoxue
 * @version 1.0
 * @CreateTime 2017/12/05 16:53:23
 * @Description data fill item
 */
public class Item {
    private Long id;
    private String name;
    private String code;
    private Long category;

    /**
     *
     * @author xuepeng
     * @CreateTime 2017/12/05 16:53:23
     */
    public Item() {
    }

    /*
     * (non-Javadoc)
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        Item other = (Item) obj;
        if (category == null) {
            if (other.category != null) {
                return false;
            }
        } else if (!category.equals(other.category)) {
            return false;
        }
        if (code == null) {
            if (other.code != null) {
                return false;
            }
        } else if (!code.equals(other.code)) {
            return false;
        }
        if (id == null) {
            if (other.id != null) {
                return false;
            }
        } else if (!id.equals(other.id)) {
            return false;
        }
        if (name == null) {
            if (other.name != null) {
                return false;
            }
        } else if (!name.equals(other.name)) {
            return false;
        }
        return true;
    }

    /**
     * @return the category
     */
    public Long getCategory() {
        return category;
    }

    /**
     * @return the code
     */
    public String getCode() {
        return code;
    }

    /**
     * @return the id
     */
    public Long getId() {
        return id;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /*
     * (non-Javadoc)
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((category == null) ? 0 : category.hashCode());
        result = prime * result + ((code == null) ? 0 : code.hashCode());
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    /**
     * @param category the category to set
     */
    public void setCategory(Long category) {
        this.category = category;
    }

    /**
     * @param code the code to set
     */
    public void setCode(String code) {
        this.code = code;
    }

    /**
     * @param id the id to set
     */
    public void setId(Long id) {
        this.id = id;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /*
     * (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        // Gson gson = new GsonBuilder (). SetPrettyPrinting (). Create ();
        Gson gson = new GsonBuilder().create();
        return gson.toJson(this);
    }

}

 

 

package test.zhizhi;

/**
 *
 * @ClassName Result
 * @author kanpiaoxue
 * @version 1.0
 * @CreateTime 2017/12/05 16:40:23
 * @Description result wrapper class
 */
public class Result<T> {
    private static final int SUCCESS_RESULT = 1;
    private static final String SUCCESS_CODE = "SUCCESS";
    private static final String SUCCESS_MESSAGE = "成功";

    private Integer result;
    private String code;
    private String message;
    private T data;

    /**
     *
     * @author xuepeng
     * @CreateTime 2017/12/05 16:40:23
     */
    public Result() {
    }

    public static <T> Result<T> success(T data) {
        Result<T> rs = new Result<T>();
        rs.setResult(SUCCESS_RESULT);
        rs.setCode(SUCCESS_CODE);
        rs.setMessage(SUCCESS_MESSAGE);
        rs.setData(data);
        return rs;
    }

    /*
     * (non-Javadoc)
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        Result<?> other = (Result<?>) obj;
        if (code == null) {
            if (other.code != null) {
                return false;
            }
        } else if (!code.equals(other.code)) {
            return false;
        }
        if (data == null) {
            if (other.data != null) {
                return false;
            }
        } else if (!data.equals(other.data)) {
            return false;
        }
        if (message == null) {
            if (other.message != null) {
                return false;
            }
        } else if (!message.equals(other.message)) {
            return false;
        }
        if (result == null) {
            if (other.result != null) {
                return false;
            }
        } else if (!result.equals(other.result)) {
            return false;
        }
        return true;
    }

    /**
     * @return the code
     */
    public String getCode() {
        return code;
    }

    /**
     * @return the data
     */
    public T getData() {
        return data;
    }

    /**
     * @return the message
     */
    public String getMessage() {
        return message;
    }

    /**
     * @return the result
     */
    public Integer getResult() {
        return result;
    }

    /*
     * (non-Javadoc)
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((code == null) ? 0 : code.hashCode());
        result = prime * result + ((data == null) ? 0 : data.hashCode());
        result = prime * result + ((message == null) ? 0 : message.hashCode());
        result = prime * result + ((this.result == null) ? 0 : this.result.hashCode());
        return result;
    }

    /**
     *
     * @return whether it was successful
     * @author xuepeng
     * @CreateTime 2017/12/05 17:16:57
     * @Description determines whether the current return result is successful
     */
    public boolean isSuccess() {
        return SUCCESS_RESULT == this.result.intValue();
    }

    /**
     * @param code the code to set
     */
    public void setCode(String code) {
        this.code = code;
    }

    /**
     * @param data the data to set
     */
    public void setData(T data) {
        this.data = data;
    }

    /**
     * @param message the message to set
     */
    public void setMessage(String message) {
        this.message = message;
    }

    /**
     * @param result the result to set
     */
    public void setResult(Integer result) {
        this.result = result;
    }

    /*
     * (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "Result [result=" + result + ", code=" + code + ", message=" + message + ", data=" + data
                + "]";
    }

}

 

package test.zhizhi;

import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;

/**
 *
 * @ClassName JSONExample
 * @author kanpiaoxue
 * @version 1.0
 * @CreateTime 2017/12/05 16:36:27
 * @Description JSON example.
 *
 *
 * pom.xml
 *              <dependency>
 *              <groupId>com.google.code.gson</groupId>
 *              <artifactId>gson</artifactId>
 *              <version>2.2.2</version>
 *              </dependency>
 *
 *              <dependency>
 *              <groupId>com.google.guava</groupId>
 *              <artifactId>guava</artifactId>
 *              <version>23.0</version>
 *              </dependency>
 */
public class JSONExample {

    /**
     *
     * @param args
     * @author xuepeng
     * @CreateTime 2017/12/05 16:36:27
     * @Description
     */
    public static void main(String[] args) {
        JSONExample example = new JSONExample();

        // Generate simulated data and simulate the json structure string returned by the HTTP request
        long size = 10L;
        List<Item> items = example.createItems(size);
        Result<List<Item>> result = example.createResult(items);
        String json = example.toJSON(result);

        System.out.println(String.format("get some json data from HTTP request:\n%s", json));

        // Start parsing the json structure string
        // 1. Determine whether the returned keys all exist. If parsing does not throw an exception, then the problem is verified
        Result<List<Item>> rs = example.fromJSON(json);

        if (rs.isSuccess()) {
            List<Item> datas = rs.getData();
            // 2. In data, the number of arrays
            System.out.println("data's size : " + datas.size());
            for (Item item : datas) {
                // 3. The total key and value of each array
                System.out.println(item);
            }
        } else {
            System.err.println(
                    String.format("ERROR: some exception occured. error message is: %s", rs.getMessage()));
        }

    }

    private List<Item> createItems(Long size) {
        List<Item> items = Lists.newArrayList();
        for (long i = 0; i < size; i++) {
            Item item = new Item();
            item.setId(i);
            item.setName("name-" + i);
            item.setCode("code-" + i);
            item.setCategory(i + 2L);
            items.add(item);
        }
        return items;
    }

    private Result<List<Item>> createResult(List<Item> items) {
        Result<List<Item>> rs = Result.success(items);
        return rs;
    }

    private Result<List<Item>> fromJSON(String json) {
        Gson gson = new GsonBuilder().create();
        Type type = new TypeToken<Result<List<Item>>>() {
        }.getType();
        Result<List<Item>> rs = gson.fromJson(json, type);
        return rs;
    }

    private String toJSON(Object obj) {
        // The role of setPrettyPrinting() is to format the json structure so that it is easy for the human eye to read. The online environment should be removed, it will increase performance consumption
        Gson gson = new GsonBuilder (). SetPrettyPrinting (). Create ();
        return gson.toJson (obj);
    }

}

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326175589&siteId=291194637