json字符串解析

基本原理:把json字符串转换为json对象,然后获取对象中的值,使用json-lib-2.4-jdk15jar包

对百度身份证验证api返回的json字符串进行解析

代码如下:

package com.zdl.ex8;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

//import org.json.JSONException;
/**
* @author 作者:superroshan
* E-mail: superroshan@163.com
* @date 创建时间:2015-6-15 下午3:49:40
* @version 1.0
* @parameter
* @since
* @return
*/
public class BaiDuApiTest {

/**
* @param urlAll
* :请求接口
* @param httpArg
* :参数
* @return 返回结果
*/
public static String request(String httpUrl, String httpArg) {
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
httpUrl = httpUrl + "?" + httpArg;

try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("GET");
// 填入apikey到HTTP header
connection.setRequestProperty("apikey", "449bcb6f457e42214e1dd6c65f257b51");
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
// {"errNum":0,"retMsg":"success","retData":{"address":"\u6cb3\u5357\u7701\u6f2f\u6cb3\u5e02","sex":"M","birthday":"1989-01-12"}}

public static void main(String[] args) {
// TODO Auto-generated method stub
String httpUrl = "http://apis.baidu.com/apistore/idservice/id";
String httpArg = "id=530624197505102205";
String jsonResult = request(httpUrl, httpArg);
System.out.println(jsonResult);
// try {
// JSONObject js=new JSONObject(jsonResult);
// JSONArray array = JSONArray.fromObject(jsonResult);
JSONObject jsStr = JSONObject.fromObject(jsonResult);
JSONObject retData=jsStr.getJSONObject("retData");
String address=retData.getString("address");
System.out.println(address);
String sex=retData.getString("sex");
if(sex.equals("M")){
System.out.println("性别:男");
}
else{
System.out.println("性别:女");

}
String birthday=retData.getString("birthday");
System.out.println(birthday);



}

}

原文地址:https://www.cnblogs.com/superroshan/p/4679729.html