JSON学习总结

来源:互联网 发布:python中编码问题 编辑:程序博客网 时间:2024/06/05 06:18

简介:
当我们把服务器的数据传输到web前端或者移动端进行显示时,一般情况下,会选择JSON格式的数据,因此JSON在开发中的应用还是十分的广泛。

JSON是当前行业内使用最为广泛deep一种数据传输格式,是开发人员必备的技能之一,选择JSON可以作为一种数据返回格式,也可以作为一种数据存储格式,大多数API用json作为返回格式,数据库也会用json格式进行数据存储,json提供了一种对象序列化的方式。

JSON基础知识
Java中两种常见的JSON处理方式
综合运用

{}大括号表示对象;
[ ]中括号表示数组;
” “双引号内是属性的值;
{“name” : “王小二”} :冒号表示后者是前者的值(这个值可以是字符串,数字,也可以是另一个数组或对象)

什么是JSON?(JSON是一种key-value键值对的存在形式)
JSON是一种与开发语言无关的、轻量级的数据格式,全称是Javascript Object Notation。

JSon:Android SDK官方的一个库。
Json是当前行业内使用最广泛的一种数据传输格式,是所有开发人员必备的技能之一。
选择Json,可以作为一种数据返回格式,也可以作为一种数据存储格式。

什么是Json,有什么优点

Json (JavaScript Object Notation),是一种与开发语言无关的、轻量级的数据格式,更确切的是,它是一种数据格式或规范,对人来说具有易读、易编写的性质,对于机器来说易于程序解析与生成。

样例:

{
“name”:“Terence,
“age”:24.8,
“birthday”:“1990-05-06”,
“school”:”HDU”,
“major”:[“计算机”,“挖掘机”],
“has_girlFriend”:false,
“car”:null,
“house”:null,
“comments”:”这是一个注释”
}


数据结构:Object、Array
基本类型:string,number,true,false,null
(1)Object
{key:value,key:value…}
key:string类型。
value:任何基本类型或数据结构。
(2)Array
[value,value…]
value:任何基本类型或数据结构

**注意:**Object中key必须是String的,而Array可以为任何基本类型或数据结构,Object是{},而Array是[]

Object:用{ },Array:用 , 分割

Object使用{ }包含的键值对结构,Key必须是string类型,value为任何基本类型或数据结构 {string : value, value}
Array使用[ ]来起始,用 , 来分隔元素[value, value]

第一个属性:后面是内容,如果是多个属于以,作为分隔符。
注意:在json中没有注释的,但是可以吧注释写在一个属性里面”comment”:”这是一个注释”,

实例:

{
“name”:”王小二”.
“age”:22.3,
“birthday”:”1993-12-1”,
“school”:”蓝翔”
“major”:[“理发”,”挖掘机”],
“has_girlfriend”:false
“car”:null,
“house”:null,
“comment”:”这是一个注释”
}
JSON里没有注释//

注意:在maven的pom.xml中引入json org.json

<dependence></dependence>

JAVA的标准json包,new JSONObject,put方法。
put(key,value)
value:null,true,false,Number,String
在put一个null的时候先new一个null的Object
大括号为对象,中括号为数组

引入依赖

    <dependency>      <groupId>org.json</groupId>      <artifactId>json</artifactId>      <version>20090211</version></dependency>

有3种方式,创建json对象,
1、使用JSONObject对象put方法来构建;
2、使用HashMap及其子类如treeMap的put方法来构建;
3、使用JavaBean来构建JSONObject对象。

出现”major”:[{“bytes”:[{},{},{},{},{},{}],”empty”:false}的可以换个org.json的新版本,亲测可用。

Maven依赖:

  <dependencies>    <dependency>    <groupId>org.json</groupId>    <artifactId>json</artifactId>    <version>20160810</version>  </dependency>

使用JsonObject实现Json

import org.json.JSONException;import org.json.JSONObject;public class JSONObjectSample {    public static void main(String[] args) {        // TODO 自动生成的方法存根        JSONObject();    }    private static void JSONObject() {        // TODO 自动生成的方法存根        JSONObject wangxiaoer = new JSONObject();        Object nullObj = null;        try {            wangxiaoer.put("name", "王小二");            wangxiaoer.put("age", 25.2);            wangxiaoer.put("birthday", "1990-01-01");            wangxiaoer.put("school", "蓝翔");            wangxiaoer.put("major", new String[] { "理发", "挖掘机" });            wangxiaoer.put("has_girlfriend", false);            wangxiaoer.put("car", nullObj);            wangxiaoer.put("house", nullObj);            wangxiaoer.put("comment", "这是一个注释");            System.out.println(wangxiaoer.toString());//转换成字符串的格式        } catch (JSONException e) {            // TODO: handle exception            e.printStackTrace();        }    }}

注意:Json中多次调用put方法对同一个key调用时,会覆盖掉前一个value。
参数为null时需要转换一下,用参数代替null。wangxiaoer.put(“car”, nullObj);
注意在json中输入数组时的做法。wangxiaoer.put(“major”, new String[] { “理发”, “挖掘机” });

使用Map来构建JSON
1、使用put()方法
2、使用Map方式,使用JSONObject(map)方法构建json格式数据

使用Map实现Json

private static void createJsonByMap(){        Map<String, Object> wangxiaoer=new HashMap<String,Object>();        Object nullObj = null;        wangxiaoer.put("name", "王小二");        wangxiaoer.put("age", 25.2);        wangxiaoer.put("birthday", "1990-01-01");        wangxiaoer.put("school", "蓝翔");        wangxiaoer.put("major", new String[] { "理发", "挖掘机" });        wangxiaoer.put("has_girlfriend", false);        wangxiaoer.put("car", nullObj);        wangxiaoer.put("house", nullObj);        wangxiaoer.put("comment", "这是一个注释");        System.out.println(new JSONObject(wangxiaoer).toString());    }

使用JavaBean来构建JSON对象

public class Diaosi {    private String name;    private String school;    private boolean has_girlfriend;    private double age;    private Object car;    private Object house;    private String[] major;    private String comment;    private String birthday;}
private static void createJsonByBean() {        Diaosi wangxiaoer = new Diaosi();        wangxiaoer.setName("王小二");        wangxiaoer.setAge(25.2);        wangxiaoer.setBirthday("1990-01-01");        wangxiaoer.setSchool("蓝翔");        wangxiaoer.setMajor(new String[] { "理发", "挖掘机" });        wangxiaoer.setHas_girlfriend(false);        wangxiaoer.setCar(null);        wangxiaoer.setHouse(null);        wangxiaoer.setComment("这是一个注释");        System.out.println(new JSONObject(wangxiaoer));    }

从文件中读取JSON
进行json:
pom.xml里依赖commons-io,从文件中读取json内容

// 声明这个文件File file = new File(ReadJSONSample.class.getResource("/wangxiaoer.json").getFile());//通过依赖  FileUtils  String content = FileUtils.readFileToString(file);//通过 JSONObject 这个对象进行处理JSONObject jsonObject = new JSONObject(content);

实例:

public class ReadJSONSample {    public static void main(String[] args) throws IOException, JSONException {        // TODO 自动生成的方法存根        File file=new File(ReadJSONSample.class.getResource("/wangxiaoer.json").getFile());        String content=FileUtils.readFileToString(file);        JSONObject jsonObject=new JSONObject(content);        System.out.println("姓名:"+jsonObject.getString("name"));        System.out.println("年龄:"+jsonObject.getDouble("age"));        System.out.println("生日:"+jsonObject.getString("birthday"));        System.out.println("学校:"+jsonObject.getString("school"));        JSONArray majorArray=jsonObject.getJSONArray("major");        for (int i = 0; i < majorArray.length(); i++) {            String m=(String) majorArray.get(i);            System.out.println("专业-"+(i+1)+":"+m);        }    }}

把文件转换成JASONOBJECT
1.获取文件,通过获取文件地址:.class.getResource();
2.获取文件内容FileUtiles.readFileTOString();
3.转换成JasonObject格式,通过getString()获取key值

maven引FileUtils相关的jar包依赖。

<dependency>    <groupId>commons-io</groupId>    <artifactId>commons-io</artifactId>    <version>2.4</version></dependency>

从文件读取JSON判断null

从文件读取json 判断null isNull

if(!jsonObject.isNull("name")){    System.out.println( + jsonObject.getString("name"))}  //

解析json:
pom.xml里一个依赖 commons-io
从文件中间读取json内容

// 声明这个文件File file = new File(ReadJSONSample.class.getResource("/wangxiaoer.json").getFile());//通过依赖  FileUtils  String content = FileUtils.readFileToString(file);//通过 JSONObject 这个对象进行处理JSONObject jsonObject = new JSONObject(content);

判断Json数据中是否有指定的信息

JSONObject jsonObject = new JSONObject(content);        if (!jsonObject.isNull("name"))            System.out.println("姓名:" + jsonObject.getString("name"));        if (!jsonObject.isNull("age"))            System.out.println("年龄:" + jsonObject.getDouble("age"));        if (!jsonObject.isNull("birthday"))            System.out.println("生日:" + jsonObject.getString("birthday"));        if (!jsonObject.isNull("school"))            System.out.println("学校:" + jsonObject.getString("school"));

总结:
java的org.json包的3种创建json的方式:
1、直接使用JSONObject的put()方法。
2、先创建HashMap键/值对,然后实例化JSONObject对象,如:new JSONObject(map)。
3、先创建Javabean对象,然后实例化JSONObject对象,如:new JSONObject(obj)。

在java获取json数据(需要依赖common.io包),首先把json文件实例化为file对象,然后用file的工具类的静态方法转换成字符串,如FileUtils.readFileToString(file),然后就可以实例化JSONObject对象了,如JSONObject(string),然后就可以通过getter方法获取各个键里的值。

读入文件FileUtils.readFileToString(new File),结果转成jsonObject使用
数据存储是数组的情况使用

JSONArray majorArray = jsonObject.getJSONArray("major");    for(int i= 0;i<majorArray.length();i++){       String  m =(String)majorArray.get(i);   }

参考视频:http://www.imooc.com/learn/523

原创粉丝点击