JSON文件的封装和解析和API接口的简单实例

来源:互联网 发布:linux c编程视频教程 编辑:程序博客网 时间:2024/06/05 14:58
json文件的编写和解析:
1.什么是json?
   Xml与json的区别?
(1).可读性方面。
JSON和XML的数据可读性基本相同,JSON和XML的可读性可谓不相上下,一边是建议的语法,一边是规范的标签形式,XML可读性较好些。
(2).可扩展性方面。
XML天生有很好的扩展性,JSON当然也有,没有什么是XML能扩展,JSON不能的。
(3).编码难度方面。
XML有丰富的编码工具,比如Dom4j、JDom等,JSON也有json.org提供的工具,但是JSON的编码明显比XML容易许多,即使不借助工具也能写出JSON的代码,可是要写好XML就不太容易了。
(4).解码难度方面。
XML的解析得考虑子节点父节点,让人头昏眼花,而JSON的解析难度几乎为0。这一点XML输的真是没话说。
(5).流行度方面。
XML已经被业界广泛的使用,而JSON才刚刚开始,但是在Ajax这个特定的领域,未来的发展一定是XML让位于JSON。到时Ajax应该变成Ajaj(Asynchronous Javascript and JSON)了。
(6).解析手段方面。
JSON和XML同样拥有丰富的解析手段。
(7).数据体积方面。
JSON相对于XML来讲,数据的体积小,传递的速度更快些。
(8).数据交互方面。
JSON与JavaScript的交互更加方便,更容易解析处理,更好的数据交互。
(9).数据描述方面。
JSON对数据的描述性比XML较差。
(10).传输速度方面。
JSON的速度要远远快于XML。
 
 
描述:
 Name:张三
 Sex:男
 Age:24
Addres:安徽省合肥市高新区
Wife:马蓉,潘金莲,范冰冰
 
 
xmL:  可扩展标记(标签)语言:安卓开发  html:标签
<student>
   <name>张三</name>
   <sex>男</sex>
   <age>24</age>
<address>安徽省合肥市高新区</address>



实例一:
import org.json.JSONArray;
import org.json.JSONObject;

public class JsonCreate2 {
public static void main(String[] args) throws Exception{
/*{
"reason": "success",
"result": {
"list": [
{
"id": "wechat_20150401071581",
"title": "号外:集宁到乌兰花的班车出事了!!!!!",
"source": "内蒙那点事儿",
"firstImg": "http://zxpic.gtimg.com/infonew/0/wechat_pics_-214279.jpg/168",
"mark": "",
"url": "http://v.juhe.cn/weixin/redirect?wid=wechat_20150401071581"
},
{
"id": "wechat_20150402028462",
"title": "【夜读】梁晓声:你追求的,就是你人生的意义",
"source": "人民日报",
"firstImg": "http://zxpic.gtimg.com/infonew/0/wechat_pics_-214521.jpg/168",
"mark": "",
"url": "http://v.juhe.cn/weixin/redirect?wid=wechat_20150402028462"
}
],
"totalPage": 16,
"ps": 20,
"pno": 1
},
"error_code": 0
}*/
JSONObject jsonObject=new JSONObject();
jsonObject.put("reason", "success");
JSONObject jsonObject2=new JSONObject();
JSONArray jsonArray=new JSONArray();
//在数组下面再定义2个json对象
JSONObject jsonObject3=new JSONObject();
jsonObject3.put("id", "wechat_20150401071581");
jsonObject3.put("title", "号外:集宁到乌兰花的班车出事了!!!!!");
JSONObject jsonObject4=new JSONObject();
jsonObject4.put("id", "wechat_20150401071123");
jsonObject4.put("title", "【夜读】梁晓声:你追求的,就是你人生的意义");
//把三四两个json对象赋值进入
jsonArray.put(jsonObject3);
jsonArray.put(jsonObject4);
jsonObject2.put("list", jsonArray);
jsonObject2.put("totalPage", "16");
jsonObject2.put("ps", "20");
jsonObject2.put("pno", "1");
jsonObject.put("result", jsonObject2);
jsonObject.put("error_code", "0");
System.out.println(jsonObject.toString());
}
}


实例二:聊天女仆(普通解析):
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Scanner;

import org.json.JSONObject;

public class 聊天女仆 {

/*
* B/S http可以支持c/s
*
* 重难点 1 HTTP协议的使用:get方法,拼接参数 2 把文字转化成utf-8格式 URLEncoder.encode(question,
* "utf-8") new String(b, "utf-8") 3 建议多使用缓存流读取互联网的内容
*
* 4 其他技巧(设置connection一些参数 返回数据可以判断是否成功) 5我们使用的是第三方的聚合数据服务器,不是用户自建的
*
* 6:返回当下最为流行的数据格式:JSON 70% xml 30% 下午:json生成 json文件解析
*
* 练习:注册聚合数据,完成实名认证,申请机器人接口,完成机器问答聊天
*/
public static void main(String[] args) throws Exception {
while (true) {
// 第一步:URL
Scanner scanner = new Scanner(System.in);
System.out.println("请输入要询问机器人的话:");
String question = scanner.next();

String str = "http://op.juhe.cn/robot/index?info="
+ URLEncoder.encode(question, "utf-8")
+ "&key=fd7e1d6211705783bef1f80336605f39";

URL url = new URL(str);

// 创建连接,发起请求
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
// 可以设置连接的一些参数
connection.setConnectTimeout(5000);// 设置超时时间为5秒
connection.setRequestMethod("GET");// 在java中,http请求的默认为get,所以可以省略

if (connection.getResponseCode() == 200) {

// 获得流,得到响应
InputStream is = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
// 输出流
byte[] b = new byte[10240];
bis.read(b);

String str2 = new String(b, "utf-8");

JSONObject jsonObject = new JSONObject(str2);

JSONObject jsonObject2 = jsonObject.getJSONObject("result");

String string = jsonObject2.getString("text");
System.out.println("机器人说:" + string);
// 关闭相关资源
is.close();
connection.disconnect();
} else {
System.out.println("请检查连接,代码有误");
}
}
}

}

实例三:带数组的解析:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class jsonArraysJiexi {
public static void main(String[] args) {
String str = "{'reason':'成功的返回','result':[{'code':100000,'text':'当然不是啦'},{'code':100001,'text':'当然不是的'},{'code':100001,'text':'当然不是哦'},],'error_code':0}";

try {JSONObject jsonObject = new JSONObject(str);
// JSONObject jsonObject2 = jsonObject.getJSONObject("result");
JSONArray array = jsonObject.getJSONArray("result");
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject2 = array.getJSONObject(i);
System.out.println(jsonObject2.getString("text"));
// System.out.println("<---------------->");
}

} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


下面给出了快速数据的一个简单的查询!:(不支持压缩包上传,后续更新,请等待!)
import java.util.Scanner;


import org.json.JSONArray;
import org.json.JSONObject;


public class 生活小助手 {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws Exception {
function fun=new function();
System.out.println("----------欢迎使用生活小助手--------");
while (true) {
System.out.println("请选择服务");
System.out.println("1.快递单号查询");
System.out.println("2.手机号码归属地查询");
System.out.println("3.身份证查询");
System.out.println("4.历史上的今天查询");
System.out.println("<------------->");

int op = scanner.nextInt();
switch (op) {
case 1:
System.out.println("快递单号");
String danhao = scanner.next();
String string=fun.expressDelivery(danhao);
System.out.println(string);
JSONObject jsonObject7 = new JSONObject(string);
JSONArray array2 = jsonObject7.getJSONArray("result");


for (int i = 0; i < array2.length(); i++) {
JSONObject jsonObject8 = array2.getJSONObject(i);
System.out.print(jsonObject8.getString("time")+"   ");
System.out.print(jsonObject8.getString("status")+"   ");
System.out.println("<---------------->");
}
System.out.println(jsonObject7.getString("issign"));
break;
case 2:
System.out.println("手机号码");
String shoujihao = scanner.next();
String string2=fun.phoneNumber(shoujihao);
JSONObject jsonObject1 = new JSONObject(string2);
JSONObject jsonObject2=jsonObject1.getJSONObject("result");
System.out.println(jsonObject2.getString("shouji"));
System.out.println(jsonObject2.getString("province"));
System.out.println(jsonObject2.getString("city"));
System.out.println(jsonObject2.getString("company"));
System.out.println(jsonObject2.getString("cardtype"));
break;
case 3:
System.out.println("身份证号");
String shengfenghao = scanner.next();
String string3=fun.IDcard(shengfenghao);
JSONObject jsonObject3 = new JSONObject(string3);
JSONObject jsonObject4=jsonObject3.getJSONObject("result");
System.out.println(jsonObject4.getString("province"));
System.out.println(jsonObject4.getString("city"));
System.out.println(jsonObject4.getString("area"));
System.out.println(jsonObject4.getString("sex"));
System.out.println(jsonObject4.getString("birth"));
break;
case 4:
System.out.println("月份");
int a=scanner.nextInt();
System.out.println("日期");
int b=scanner.nextInt();
//String string4=fun.lastYearOnceMore(a,b);

JSONObject jsonObject5 = new JSONObject(function.getHistoryToday(a, b));
JSONArray array = jsonObject5.getJSONArray("result");

for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject6 = array.getJSONObject(i);
System.out.print(jsonObject6.getString("title")+"   ");
System.out.print(jsonObject6.getString("year")+"   ");
System.out.print(jsonObject6.getString("content")+"   ");
System.out.print("<---------------->");
}
break;
default:
System.err.println("有错误,请DEBUG");
break;
}
}
}
}



由于我在极速数据上注册的API接口使用次数有限,就不提供key值了,抱歉!需要用到的可以自行注册:

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;


public class function {
String  Httconnction(String str)throws Exception{
URL url = new URL(str);
// 创建连接,发起请求
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 可以设置连接的一些参数
connection.setConnectTimeout(5000);// 设置超时时间为5秒
connection.setRequestMethod("GET");// 在java中,http请求的默认为get,所以可以省略
String str2="";
if (connection.getResponseCode() == 200) {
// 获得流,得到响应
InputStream is = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
// 输出流
byte[] b = new byte[10240];
bis.read(b);
str2 = new String(b, "utf-8");
is.close();
connection.disconnect();

return str2;
}

String  expressDelivery(String question)throws Exception{
String str = "http://api.jisuapi.com/express/query?appkey=你的KEY&type=auto&number="
+ URLEncoder.encode(question,"utf-8");
return Httconnction(str);
}

  String phoneNumber(String question) throws Exception {
String str = "http://api.jisuapi.com/shouji/query?appkey=你的KEY&shouji="
+ URLEncoder.encode(question,"utf-8");
return Httconnction(str);
}
  String IDcard(String question) throws Exception {
String str = "http://api.jisuapi.com/idcard/query?appkey=你的KEY&idcard="
+ URLEncoder.encode(question,"utf-8");
return Httconnction(str);

  String lastYearOnceMore(int a,int b) throws Exception {
String str = "http://api.jisuapi.com/todayhistory/query?你的KEY&month="
+a+"&day="+b;
return Httconnction(str);
}
  public static String getHistoryToday(int month, int date) {
      URL url = null;
      BufferedReader reader = null;
      HttpURLConnection huc = null;
      String fallback = null;
      String querry = "http://api.jisuapi.com/todayhistory/query?appkey=22930282477fe152&month="+ month +"&day=" + date;
      try {
          url = new URL(querry);
          huc = (HttpURLConnection) url.openConnection();
          if (huc.getResponseCode() == 200) {
              reader = new BufferedReader(new InputStreamReader(huc.getInputStream(), "UTF-8"));
              fallback = reader.readLine();
          }
      } catch (IOException e) {
          e.printStackTrace();
      } finally {
          try {
              reader.close();
          } catch (IOException e) {
              e.printStackTrace();
          }
          huc.disconnect();
      }
      return fallback;
  }
}