Java学习笔记:JSON

JSON是什么

  • JSON(JavaScript Object Notation)是一种轻量级的文本数据交换格式;
  • JSON独立于语言;
  • JSON 具有自我描述性。

 

JSON语法结构

  • 数据结构

        Object:使用花括号 {} 包含的键值对结构(key必须是string类型,value为任何基本类型或数据结构,逗号分隔数据)。
        Array:使用中括号 [] 来表示,并用逗号来分隔元素。

  • 基本类型

        string、number、true、false、null。

  • 示例

       movie.json

{
    "name": "悬崖之上",
    "year": 2021,
    "director": "张艺谋",
    "actors": ["张译","于和伟","秦海璐"]
}

 

JSON怎么用

        (以Google的Gson为例)

  • 将对象转换为JSON字符串:

        String json = new Gson().toJSON(要转换的对象);

//1. 创建
Gson g = new Gson();
//2. 转换
Movie m = new Movie("悬崖之上",2021,"张艺谋");
String s = new Gson().toJson(m);
  • 将JSON字符串转换为对象:

        对象 = new Gson().fromJson(JSON字符串,对象类型.class);

//1. 创建
Gson g = new Gson();
//2. 转换
HashMap data = g.fromJson("{\"name\":\"悬崖之上\",\"year\":2021,\"director\":\"张艺谋\",\"actors\":[\"张译\",\"于和伟\",\"秦海璐\"]}", HashMap.class);

 

编程实例

一个在线查询手机号码归属地的程序,用到Alibaba的FastJson来解析收到的Json数据

import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class Task1 {
    // 手机归属地查询接口地址
    public static String API_URL = "http://apis.juhe.cn/mobile/get";
    // 接口请求Key
    public static String API_KEY = "24ff**********************5ed8";

    public static void main(String[] args) {
        String mobile = "13901020304";
        queryMobileLocation(mobile);
    }

    /**
     * 根据手机号码/手机号码前7位查询号码归属地
     * @param mobile
     */
    public static void queryMobileLocation(String mobile)
    {
        Map<String, Object> params = new HashMap<>();//组合参数
        params.put("phone", mobile);
        params.put("key", API_KEY);
        String queryParams = urlEncode(params);

        String response = doGet(API_URL, queryParams);
        try {
            JSONObject jsonObject = (JSONObject) JSONObject.parse(response);
            if (jsonObject.getIntValue("error_code") == 0) {
                JSONObject result = jsonObject.getJSONObject("result");

                System.out.printf("省份:%s%n", result.getString("province"));
                System.out.printf("城市:%s%n", result.getString("city"));
                System.out.printf("运营商:%s%n", result.getString("company"));

            } else {
                System.out.println("调用接口失败:" + jsonObject.getString("reason"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * get方式的http请求
     * @param httpUrl 请求地址
     * @return 返回结果
     */
    public static String doGet(String httpUrl, String queryParams) {
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        String result = null;// 返回结果字符串
        try {
            // 创建远程url连接对象
            URL url = new URL(new StringBuffer(httpUrl).append("?").append(queryParams).toString());
            // 通过远程url连接对象打开一个连接,强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式:get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间
            connection.setConnectTimeout(5000);
            // 设置读取远程返回的数据时间
            connection.setReadTimeout(6000);
            // 发送请求
            connection.connect();
            // 通过connection连接,获取输入流
            if (connection.getResponseCode() == 200) {
                inputStream = connection.getInputStream();
                // 封装输入流,并指定字符集
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                // 存放数据
                StringBuilder sbf = new StringBuilder();
                String temp;
                while ((temp = bufferedReader.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append(System.getProperty("line.separator"));
                }
                result = sbf.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != bufferedReader) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();// 关闭远程连接
            }
        }
        return result;
    }

    /**
     * 将map型转为请求参数型
     * @param data
     * @return
     */
    public static String urlEncode(Map<String, ?> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, ?> i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        String result = sb.toString();
        result = result.substring(0, result.lastIndexOf("&"));
        return result;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值