首页 > 代码库 > 解析json常用几种方式

解析json常用几种方式

1.使用Google 的 gson方式解析json,园子里面对json方面的教程都非常多,很多写的都非常不错,借鉴不少,毕竟刚刚研究.

gson支持解析的类型还是比较全面的,包括JavaBean,List<JavaBean>,List<String>,Map等,使用起来也是比较方便.

首先配置环境,需要下载相应的jar包, 下面测试使用的版本是2.2.4.

官方下载地址:http://code.google.com/p/google-gson/

gson API:http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/index.html

 

测试用例(源码附件GsonJson.zip,下载地址:http://pan.baidu.com/s/1qWHNjdU):

public class MyGson {        private Gson gson = new Gson();         //java bean to json string    @Test    public void beanToJson(){        Person person  = new Person();        person.setId(1);        person.setName("zhanglu");        person.setAddress("湖北大悟");        System.out.println(gson.toJson(person));    }    //json string to java bean    @Test    public void jsonTobean(){        String json = "{‘id‘:‘1‘,‘name‘:‘zhang‘,‘address‘:‘Hubei‘}";        Person person = gson.fromJson(json, Person.class);        System.out.println(person);    }        //list<bean> to json    @Test    public void listBeanToJson(){        Person person1 = new Person(1, "zhang", "Hubei");        Person person2 = new Person(2,"lu","DaWu");        List<Person> persons = new ArrayList<>();        persons.add(person1);        persons.add(person2);        String json = gson.toJson(persons);        System.out.println(json);    }        //json to list<bean>    @Test    public void jsonToListBean(){        String json = "[{‘id‘:‘1‘,‘name‘:‘zhang‘,‘address‘:‘Hubei‘},{‘id‘:‘2‘,‘name‘:‘lu‘,‘address‘:‘DaWu‘}]";        List<Person> persons = gson.fromJson(json, new TypeToken<List<Person>>(){}.getType());        for(Person per : persons){            System.out.println(per);        }    }            //list string to string    @Test    public void listStringToJson(){        List<String> list = new ArrayList<>();        list.add("zhanglu");        list.add("hubei");        list.add("Dawu");        String json = gson.toJson(list);        System.out.println(json);    }        //json string to list<string>    @Test    public void jsonToListString(){        String json = "[‘zhanglu‘,‘hubei‘,‘Dawu‘]";        List<String> list = gson.fromJson(json, new TypeToken<List<String>>(){}.getType());        for(String str : list){            System.out.println(str);        }    }        //Map<String,object> to json    @Test    public void mapToJson(){        Map<String, Person> map = new HashMap<>();        Person person = new Person(1, "zhanglu", "湖北大悟");        Person person2 = new Person(2, "Alone", "HuBeiDaWu");        map.put("person", person);        map.put("person2", person2);        String json = gson.toJson(map);        System.out.println(json);    }        //json to Map<Stirng,Object>    @Test    public void jsonToMap(){        String json = "{‘person‘:{‘id‘:1,‘name‘:‘zhanglu‘,‘address‘:‘湖北大悟‘},‘person2‘:{‘id‘:2,‘name‘:‘Alone‘,‘address‘:‘HuBeiDaWu‘}}";        Map<String, Person> map = gson.fromJson(json, new TypeToken<Map<String,Person>>(){}.getType());        for(String str : map.keySet()){            System.out.println("key:"+str);            System.out.println((Person)map.get(str));        }    }        //test refrences obj    //如果双向引用, 会产生死循环,  方法1, 在需要被过滤的字段上加上修饰符transient, Cat的animail加上了    //方法1:排除transient字段    /*//方法2:排除Modifier为指定类型的字段Gson gson = new GsonBuilder().excludeFieldsWithModifiers(Modifier.PROTECTED) // <---.create();*/    //方法3:使用@Expose注解,注意,没有被 @Expose 标注的字段会被排除,如下所示:    @Test    public void testReferences(){        Animail animail = new Animail();        animail.setName("Animial");        Cat cat = new Cat();        cat.setId(1);        cat.setName("Cat1");        cat.setAnimail(animail);        Cat cat2 = new Cat();        cat2.setId(2);        cat2.setName("Cat2");        cat.setAnimail(animail);        List<Cat> cats  = new ArrayList<>();        cats.add(cat2);        cats.add(cat);        animail.setCatlist(cats);        String json = gson.toJson(animail);        System.out.println(json);    }        //方法4:使用ExclusionStrategy定制字段排除策略,这种方式最灵活,下面的例子把所有以下划线开头的字段全部都排除掉:    @Test    public void ExclusionStrategy(){        ClassInfo classInfo = new ClassInfo();        classInfo.setClassNo("C0001");        classInfo.setClassName("Java_1");        StudentInfo stu1 = new StudentInfo();        stu1.setStuId(1);        stu1.setStuName(1);        StudentInfo stu2 = new StudentInfo();        stu2.setStuId(1);        stu2.setStuName(1);        stu1.setClassInfo(classInfo);        stu2.setClassInfo(classInfo);        List<StudentInfo> stulist = new ArrayList<>();        stulist.add(stu2);        stulist.add(stu1);        classInfo.setStudentslist(stulist);        ExclusionStrategy myExclusionStrategy = new ExclusionStrategy() {              @Override              public boolean shouldSkipField(FieldAttributes fa) {                  return fa.getName().equals("classInfo");              }              @Override              public boolean shouldSkipClass(Class<?> clazz) {                  return false;              }         };        Gson gson = new GsonBuilder().setExclusionStrategies(myExclusionStrategy).create();        String json = gson.toJson(classInfo);        System.out.println(json);    }}

 

2.使用阿里的fastJson方式解析json,阿里官方介绍说这个比gson效率更高速度更快,使用fastJson的人也非常多,至少我有些同学公司里面在使用, 不乏游戏开发在使用,也有人说有Bug,具体我也没有对两者进行比较测试.

fastJson同样支持常用的数据类型解析,还提供了大文本解析和对时间类型的解析方式,同样也有android版本jar, 但是这个不是C#的FastJson, 首字母大小写是不一样的, 也不是同一个东西, 不可混为一谈.

官网文档::https://github.com/alibaba/fastjson/wiki/常见问题

笔者测试使用的版本是1.1.41,下载地址:http://repo1.maven.org/maven2/com/alibaba/fastjson/1.1.41/

fastJson其它版本官方下载地址:http://repo1.maven.org/maven2/com/alibaba/fastjson/

maven配置:

<dependency>     <groupId>com.alibaba</groupId>     <artifactId>fastjson</artifactId>     <version>1.1.41</version></dependency>

测试用例(源码附件fastJson.zip,下载地址:http://pan.baidu.com/s/1pJE1xsZ):

public class FastJsonTest {    // Java bean to json    @Test    public void JavaBeanToJson() {        Person person = new Person(1, "zhanglu", "Hubei");        String json = JSON.toJSONString(person);        System.out.println(json);    }    // Json to Javabean    @Test    public void JsonToJavaBean() {        String json = "{‘address‘:‘Hubei‘,‘id‘:1,‘name‘:‘zhanglu‘}";        Person person = JSON.parseObject(json, Person.class);        System.out.println(person);    }    // List<JavaBean> to json    @Test    public void listJavaBeanToJson() {        Person p1 = new Person(1, "zhanglu", "Hubei");        Person p2 = new Person(2, "wukang", "Hubei");        List<Person> personlist = new ArrayList<>();        personlist.add(p1);        personlist.add(p2);        String json = JSON.toJSONString(personlist);        System.out.println(json);    }    // Json to List<JavaBean>    @Test    public void JsonToListBean() {        String json = "[{‘address‘:‘Hubei‘,‘id‘:1,‘name‘:‘zhanglu‘},{‘address‘:‘Hubei‘,‘id‘:2,‘name‘:‘wukang‘}]";        List<Person> persons = JSON.parseArray(json, Person.class);        for (Person person : persons) {            System.out.println(person);        }    }    // List<String> to json    @Test    public void listStringToJson() {        List<String> list = new ArrayList<>();        list.add("zhanglu");        list.add("wukang");        String json = JSON.toJSONString(list);        System.out.println(json);    }    // json to List<String>    @Test    public void JsonToListString() {        String json = "[‘zhanglu‘,‘wukang‘]";        List<String> list = JSON.parseArray(json, String.class);        for (String str : list) {            System.out.println(str);        }    }    // Map<String,Object> to json    @Test    public void MapToJson() {        Map<String, Person> map = new HashMap<>();        map.put("person1", new Person(1, "zhanglu", "Hubei"));        map.put("person2", new Person(2, "wukang", "Hubei"));        String json = JSON.toJSONString(map);        System.out.println(json);    }    // Json to Map<String,JavaBean>    @Test    public void JsonToMap() {        String json = "{‘person1‘:{‘address‘:‘Hubei‘,‘id‘:1,‘name‘:‘zhanglu‘},‘person2‘:{‘address‘:‘Hubei‘,‘id‘:2,‘name‘:‘wukang‘}}";        Map<String, Person> map = JSON.parseObject(json,                new TypeReference<Map<String, Person>>() {                });        for (String key : map.keySet()) {            System.out.println("key:" + key);            System.out.println(map.get(key));        }    }    // Test references javaBean    // Animail,Cat    @Test    public void TestReferences() {        Animail animail = new Animail();        animail.setName("animial");        Cat cat = new Cat();        cat.setId(1);        cat.setName("MiMi");        Cat cat2 = new Cat();        cat2.setId(1);        cat2.setName("CiCi");        cat.setAnimail(animail);        cat2.setAnimail(animail);        List<Cat> catlist = new ArrayList<>();        catlist.add(cat2);        catlist.add(cat);        animail.setCatlist(catlist);        String json = JSON.toJSONString(animail);        System.out.println(json);    }    // Test references javaBean    // Animail,Cat    @Test    public void TestReferences2() {        Animail animail = new Animail();        animail.setName("animial");        Cat cat = new Cat();        cat.setId(1);        cat.setName("MiMi");        Cat cat2 = new Cat();        cat2.setId(1);        cat2.setName("CiCi");        cat.setAnimail(animail);        cat2.setAnimail(animail);        List<Cat> catlist = new ArrayList<>();        catlist.add(cat2);        catlist.add(cat);        animail.setCatlist(catlist);        String json = JSON.toJSONString(animail,SerializerFeature.DisableCircularReferenceDetect);        System.out.println(json);    }    // methods 01 transient    // @JSONField(serialize=false)        // Date to Json    @Test    public void DateToJson(){        StudentInfo studentInfo = new StudentInfo();        studentInfo.setBirthday(new Date());        studentInfo.setId(1);        JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd";        String json = JSON.toJSONString(studentInfo,SerializerFeature.WriteDateUseDateFormat);        System.out.println(json);    }}

 

解析json常用几种方式