| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
jopen
10年前发布

Java Json 序列化与反序列化

JSON</strong>(JavaScript Object Notation) 是一种轻量级的数据交换格式。 易于人阅读和编写。同时也易于机器解析和生成。 它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一个子集。 JSON采用完全独立于语言的文本格式,这些特性使JSON成为理想的数据交换语言。</span>


下面介绍两款自己在开发中常用的处理Json的Java开源类库:Gson和Fastjson

1、Gson

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

Gson官网:http://code.google.com/p/google-gson/

Gson User Guide:https://sites.google.com/site/gson/gson-user-guide



2、Fastjson

Fastjson是一个json处理工具包,由阿里巴巴公司开发,包括“序列化”和“反序列化”两部分,它具备如下特征:

  1. 速度最快,测试表明,fastjson具有极快的性能,超越任其他的java json parser。包括自称最快的jackson。
  2. 功能强大,完全支持java bean、集合、Map、日期、Enum,支持范型,支持自省。
  3. 无依赖,能够直接运行在Java SE 5.0以上版本
  4. 支持Android。
  5. 开源 (Apache 2.0)
Fastjson 官网:http://code.alibabatech.com/wiki/display/FastJSON/Overview


下面通过一个简单Demo,对比两者 序列化与反序列化的用法

JavaBean 实体Person

    package com.example.testjson.entity;                import java.util.Date;        import java.util.List;        import java.util.Map;                public class Person {            private String name;            private FullName fullName;            private int age;            private Date birthday;            private List<String> hobbies;            private Map<String, String> clothes;            private List<Person> friends;                        public String getName() {                return name;            }                    public void setName(String name) {                this.name = name;            }                    public FullName getFullName() {                return fullName;            }                    public void setFullName(FullName fullName) {                this.fullName = fullName;            }                    public int getAge() {                return age;            }                    public void setAge(int age) {                this.age = age;            }                    public Date getBirthday() {                return birthday;            }                    public void setBirthday(Date birthday) {                this.birthday = birthday;            }                    public List<String> getHobbies() {                return hobbies;            }                    public void setHobbies(List<String> hobbies) {                this.hobbies = hobbies;            }                    public Map<String, String> getClothes() {                return clothes;            }                    public void setClothes(Map<String, String> clothes) {                this.clothes = clothes;            }                    public List<Person> getFriends() {                return friends;            }                    public void setFriends(List<Person> friends) {                this.friends = friends;            }                    @Override            public String toString() {                String str= "Person [name=" + name + ", fullName=" + fullName + ", age="                        + age + ", birthday=" + birthday + ", hobbies=" + hobbies                        + ", clothes=" + clothes +  "]\n";                if(friends!=null){                    str+="Friends:\n";                    for (Person f : friends) {                        str+="\t"+f;                    }                }                return str;            }                    }                class FullName {            private String firstName;            private String middleName;            private String lastName;                        public FullName(){            }                        public FullName(String firstName, String middleName, String lastName) {                super();                this.firstName = firstName;                this.middleName = middleName;                this.lastName = lastName;            }                    public String getFirstName() {                return firstName;            }                    public void setFirstName(String firstName) {                this.firstName = firstName;            }                    public String getMiddleName() {                return middleName;            }                    public void setMiddleName(String middleName) {                this.middleName = middleName;            }                    public String getLastName() {                return lastName;            }                    public void setLastName(String lastName) {                this.lastName = lastName;            }                    @Override            public String toString() {                return "[firstName=" + firstName + ", middleName="                        + middleName + ", lastName=" + lastName + "]";            }                    }  
</div> </div>

</div>
负责创建Person的Bean Factory
    package com.example.testjson.entity;                import java.util.ArrayList;        import java.util.HashMap;        import java.util.List;        import java.util.Map;                public class PersonFactory {                        private static Person createABSPerson(String name,List<Person> friends) {                Person newPerson = new Person();                newPerson.setName(name);                newPerson.setFullName(new FullName(name+"_first", name+"_middle", name+"_last"));                newPerson.setAge(24);                List<String> hobbies=new ArrayList<String>();                hobbies.add("篮球");                hobbies.add("游泳");                hobbies.add("coding");                newPerson.setHobbies(hobbies);                Map<String,String> clothes=new HashMap<String, String>();                clothes.put("coat", "Nike");                clothes.put("trousers", "adidas");                clothes.put("shoes", "安踏");                newPerson.setClothes(clothes);                newPerson.setFriends(friends);                return newPerson;            }                        public static Person create(String name){                List<Person> friends=new ArrayList<Person>();                friends.add(createABSPerson("小明",null));                friends.add(createABSPerson("Tony",null));                friends.add(createABSPerson("陈小二",null));                        return createABSPerson(name,friends);            }        }  
</div> </div>

</div>
Gson 工具类GsonUtil

</div> </div>
    package com.example.testjson.gson;                import com.google.gson.Gson;        import com.google.gson.GsonBuilder;        import com.google.gson.JsonElement;        import com.google.gson.JsonParser;                public class GsonUtil {        private static Gson gson = new GsonBuilder().create();                        public static String bean2Json(Object obj){                return gson.toJson(obj);            }                        public static <T> T json2Bean(String jsonStr,Class<T> objClass){                return gson.fromJson(jsonStr, objClass);            }                        public static String jsonFormatter(String uglyJsonStr){                Gson gson = new GsonBuilder().setPrettyPrinting().create();                JsonParser jp = new JsonParser();                JsonElement je = jp.parse(uglyJsonStr);                String prettyJsonString = gson.toJson(je);                return prettyJsonString;            }        }  


</div>

Fastjson 工具类FastJsonUtil

</div> </div>
    package com.example.testjson.fastjson;                import com.alibaba.fastjson.JSON;                public class FastJsonUtil {                        public static String bean2Json(Object obj){                return JSON.toJSONString(obj);            }                        public static <T> T json2Bean(String jsonStr,Class<T> objClass){                return JSON.parseObject(jsonStr, objClass);            }        }  


</div>
最后两个测试类

GsonTest
    package com.example.testjson;                import com.example.testjson.entity.Person;        import com.example.testjson.entity.PersonFactory;        import com.example.testjson.gson.GsonUtil;                public class GsonTest {                    /**            * @param args            */            public static void main(String[] args) {                // TODO Auto-generated method stub                Person p = PersonFactory.create("Kobe");                String json = GsonUtil.bean2Json(p);                String prettyJsonString = GsonUtil.jsonFormatter(json);                                System.out.println("FastJson Serializing="+json);                System.out.println("FastJson Serializing PrettyPrinting="+prettyJsonString);                                Person newPerson = GsonUtil.json2Bean(json, Person.class);                                System.out.println("FastJson Deserializing="+newPerson);            }                }  
</div> </div>

</div>
FastJsonTest

package com.example.testjson;        import com.example.testjson.entity.Person;    import com.example.testjson.entity.PersonFactory;    import com.example.testjson.fastjson.FastJsonUtil;        public class FastJsonTest {            /**        * @param args        */        public static void main(String[] args) {            // TODO Auto-generated method stub                Person p = PersonFactory.create("Kobe");            String json = FastJsonUtil.bean2Json(p);                        System.out.println("FastJson Serializing="+json);                        Person newPerson = FastJsonUtil.json2Bean(json, Person.class);                        System.out.println("FastJson Deserializing="+newPerson);        }        }  
</div> </div>

 本文由用户 jopen 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
 转载本站原创文章,请注明出处,并保留原始链接、图片水印。
 本站是一个以用户分享为主的开源技术平台,欢迎各类分享!