JSON学习心得

来源:互联网 发布:php直播间源码 编辑:程序博客网 时间:2024/06/08 02:44

一、Json中的数据类型的表示方式

(1)、对象

使用{ }和键值对的形式来表示一个对象,其中key必须是string类型的,值可以是基本数据类型或者结构数据类型。

(2)、数组

使用[ ]来表示一个数组的开始和结束,用‘,’来分割不同的数组元素,数组元素可以是基本数据类型和对象等。

二、实例

(1)、创建json对象

需要注意的是在使用JSONObject对象时需要导入一个

import org.json.JSONException;
import org.json.JSONObject;

private static void JsonObject(){
        JSONObject duan = new JSONObject();
        try {
            duan.put("name", "xxxx");
            duan.put("age", 22);
            duan.put("ID", "20120406");
            duan.put("school", "Uestc");
            duan.put("MajorCourse", new String[] {"math", "english"});

            System.out.println(duan.toString());
        } catch (JSONException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

(2)、json对象的解析

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
 * Created with IntelliJ IDEA.
 * User: shuaiy
 * Date: 16-9-25
 * Time: 下午3:07
 * To change this template use File | Settings | File Templates.
 */
public class ReadJson {
    public static void main(String args[]) throws JSONException {
        String content = getAllString();
       // System.out.println(content);
        JSONObject jsonObject = new JSONObject(content);
        System.out.println("the name is :" + jsonObject.getString("name"));
        System.out.println("the age is :" + jsonObject.getInt("age"));
        System.out.println("the ID is :" + jsonObject.getString("ID"));
        System.out.println("the school is :" + jsonObject.getString("school"));
        JSONArray majorCourse = jsonObject.getJSONArray("MajorCourse");
        for(int i = 0;i<majorCourse.length();i++){                                 //对数组的处理
            System.out.println("the course is :" + majorCourse.get(i));
        }
    }

    public static String getAllString(){
        File file = new File("E:\\json\\readFile\\src\\read", "12.txt");
        Long filelength = file.length();
        byte[] content = new byte[filelength.intValue()];
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        try {
            in.read(content);
            in.close();
        } catch (IOException e1) {
            e1.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return new String(content);
    }

}
需要注意的是在Json解析的过程中,对于数组的处理需要注意借助于JsonArray数组,然后进行遍历操作即可。在进行打印输出的同时可以使用 IsNull()方法判断
所获取到的对象是否为空,然后再进行后续的处理。


0 0