Json与Gson

2017-07-27  本文已影响0人  ccq_inori

JSON(JavaScript Object Notation)是一种轻量级的数据交换语言,以文字为基础,且易于让人阅读,同时也方便了机器进行解析和生成。JSON简单说就是javascript中的对象和数组,所以这两种结构就是对象和数组两种结构,通过这两种结构可以表示各种复杂的结构,其可以将JavaScript 对象中表示的一组数据转换为字符串,然后就可以在函数之间轻松地传递这个字符串,或者在异步应用程序中将字符串从Web客户机传递给服务器端程序。JSON采用完全独立于程序语言的文本格式,但是也使用了类C语言的习惯(包括C、C++、C#、Java、JavaScript、Perl、Python等)。这些特性使JSON成为理想的数据交换语言。

Json有两种数据结构:数组和对象

对象:是指用{}中间的内容,其形式为{key:value,key1:value1,key2:value2}

k#ey为对象的属性,而value为对象的属性值,通过对应的key值来取出对应的value值

数组:是指用[]中间的内容,其形式为["java","javascript",servlet],跟java,c,c++等语言一样的数组
可以通过下标,索引来取出对应的值

下面介绍Json与Gson的使用方法
首先我们先导入我们所需的包: (http://pan.baidu.com/s/1eSJ4mBK) 密码:6j47

搜狗截图17年07月27日0929_1.png

**Json的值也就是上面所说的value值,它有几种类型,数字(包括整形和浮点型),字符串,逻辑值,数组,对象,null,它们可以直接使用,对应相应的key **

直接使用JSONObject对象

    /**
     * 直接使用JSONObject对象
     */
    private static void JSONObject()
    {
        Object nullObj=null;
        //创建一个JSONObject对象
        JSONObject jsonObject=new JSONObject();  //很类似于Map<String,Object>,后面讲到
        jsonObject.put("name","小明");
       //使用浮点型
        jsonObject.put("age",25.2);
      //json没有Data类型
        jsonObject.put("birthday","1990-10-01");
        jsonObject.put("school","蓝翔");
     //数组类型
        jsonObject.put("major",new String[]{"挖掘机"});
        jsonObject.put("house", nullObj);
        System.out.println(jsonObject);
    }

其结果为


搜狗截图17年07月27日0944_2.png

通过Map来使用json

    /**
     * 通过Map来使用json
     */
    private static void createJsonByMap()
    {
        //创建一个Map对象
        Map<String,Object> jsonObjectMap=new HashMap<String,Object>();
        jsonObjectMap.put("name","王小二");
        jsonObjectMap.put("age",25.2);
        jsonObjectMap.put("birthday","1990-10-01");
        jsonObjectMap.put("school","蓝翔");
        jsonObjectMap.put("major",new String[]{"理发","挖掘机"});
        jsonObjectMap.put("house", null);
        System.out.println(new JSONObject(jsonObjectMap));
    }
搜狗截图17年07月27日0946_3.png

下面推荐使用这种方法来使用json

/**
     * 这个是通过bean的形式来使用json
     */
    private static void createJsonByBean()
    {
        
        JSONObject jsonObject =new JSONObject();
        //定义一个bean
        Person person=new Person();
        //调用set方法
        person.setId("1");
        person.setName("王小二");
        person.setAge("18");
        person.setSex("男");
        //通过这个方法来使bean成为JSONObject对象
        JSONObject j1=jsonObject.fromObject(person);
        //判断是否为空
        if(!j1.isEmpty())
        {
            System.out.println(j1);
        }

    }

JSON也可以通过文件来读取里面的jSON数据

public static void main(String[] args) throws IOException
    {
    public static void main(String[] args) throws IOException 
      {
        //从文件中读取json数据
        File file=new File(ReadGson.class.getResource("/Json/wangxiaoer.json").getFile());
        String content=FileUtils.readFileToString(file);
        //解析成一个json对象
        JSONObject jsonObject=new JSONObject(content);
        //找到一个名为name的key
        System.out.println(jsonObject.getString("name"));
      }
    }

JSON到这里就结束了

接下来是介绍Gson的使用:(Gson可以将下面四种数据类型转换成json字符串)

类型一:JavaBean

类型二:List<JavaBean>

类型三:List<String>

类型四:List<Map<String,Object>>

private static void createGSON()
    {
        /**
         * List<javabean>对象转换json字符串
         * 将json字符串解析成List<javabean>对象
         */
        //创建一个bean对象
        Person person=new Person();
        person.setId("1");  
        person.setName("王小二");
        person.setAge("18");
        person.setSex("男");
        person.setMajor(new String[]{"理发","挖掘机"});
        //创建一个Gson
        Gson gson=new Gson();
        //将一个javabean转换成json字符串
        String jsonString=gson.toJson(person);
        System.out.println("Json字符串:"+jsonString);
        //将json字符串转换成javabean
        person=gson.fromJson(jsonString, Person.class);
        System.out.println("bean:"+person.toString());
        System.out.println();
        
        /**
         * List<String>对象转换json字符串
         * 将json字符串解析成List<String>对象
         */
        List<String> list=new ArrayList<String>();
        list.add("gson1");
        list.add("json2");
        list.add("json3");
        //将List<String>对象转换成json字符串
        jsonString=gson.toJson(list);
        System.out.println("Json字符串:"+jsonString);
        //将json字符串转换成List<String>
        List<String> list2=gson.fromJson(jsonString,list.getClass());
        System.out.println("List<String>:"+list);
        System.out.println();

        /**
         * 将List<Map<String,Object>>对象转换成json
         * 将json字符串解析成List<Map<String,Object>对象
         */
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("key1", "value1");
        map.put("key2", "value2");
        //将Map<String,Object>对象转换成json字符串
        jsonString=gson.toJson(map);
        System.out.println("Json字符串:"+jsonString);
        //将json字符串转换成Map<String,Object>
        Map<String,Object> map2=gson.fromJson(jsonString,map.getClass());
        System.out.println("List<Map<String,Object>:"+map2);
    }
搜狗截图17年07月27日1007_4.png

Gson也能读取JSON文件下的json字符串

public static void main(String[] args) throws IOException
    {
        //从文件中读取json数据
        File file=new File(ReadGson.class.getResource("/Json/wangxiaoer.json").getFile());
        String content=FileUtils.readFileToString(file);
        Gson gson=new Gson();
        //JSON只能解析成它自己的Oject对象
        //GSON能解析成自己的Oject对象
        //正向生成的对象与反向解析的对象是一样的话,可以确保两个对象是一致的
        Person person=gson.fromJson(content,Person.class);
        System.out.println(person.toString());
    }
上一篇 下一篇

猜你喜欢

热点阅读