欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

google的json库gson使用示例,jsongson,gson是一个json库

来源: javaer 分享于  点击 5991 次 点评:136

google的json库gson使用示例,jsongson,gson是一个json库


gson是一个json库,它可以方便的转换java bean成json对象,也可以方便的将json对象转换为java bean。

其项目地址:https://code.google.com/p/google-gson/

package example.jacky.json;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Map;import com.google.gson.Gson;import com.google.gson.GsonBuilder;public class People {    private int id;    private String name;    private float height;    private double weight;    private List friends = new ArrayList();    private Map info = new HashMap();    private Date birthday;    private String comment;    public People(){        id = 123456;        name = "Jacky";        height = new Float(172.2);        weight = new Double(61.236);        friends.add("Sam");        friends.add("Jimmy");        info.put("country","Taiwan");        info.put("city","Taipei");        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");        try {            birthday = sdf.parse("1989-08-09");        } catch (ParseException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        comment = null;    }    public String toString(){        String str = "";        str += "id="+id;        str += " name="+name;        str += " height="+height;        str += " weight="+weight;        str += " ...etc";        return str;    }    public static void main(String[] args) {        People p = new People();        //Gson gson = new Gson();        //If you wanna allow null object        Gson gson = new GsonBuilder().serializeNulls().create();        String str = gson.toJson(p);        System.out.println(str);        People p2 = gson.fromJson(str, People.class);        System.out.println(p2.toString());    }}

比起官方的Lib,Gson除了提供原本的Json相关功能外,更包含了Json和Java Object的互相转换,而且许多常见的类型也可以转换,特別是collection集合,非常方便

相关栏目:

用户点评