{
"error_code": 0,
"reason": "Success",
"result": {data":{
translation":["book"],
basic":{
phonetic":"shū",
explains":["[图情] book","write","letter","script"]},
query":"书",
web":[
value":["Book","Business Plan","a book"],"key":"书"},
value":["Ecclesiastes","Ecclésiaste","コヘレトの言葉"],"key":"传道书"},
value":["Book of Sui","Livre des Sui","隋書"],"key":"隋书"}
]
}
}
}
上面是要获取的json字符串,然后对应的java对象
package youdao.yf.com;
/**
* Created by Administrator on 2016/2/19.
*/
//根据获取json对象,对应的java对象,
public class YouDaoBean {
private String reason;
private Result result;
private int error_code;
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
public int getError_code() {
return error_code;
}
public void setError_code(int error_code) {
this.error_code = error_code;
}
public class Result {
private mData data;
public mData getData() {
return data;
}
public void setData(mData data) {
this.data = data;
}
public class mData {
private String[] translation;
private mBasic basic;
private String query;
public String[] getTranslation() {
return translation;
}
public void setTranslation(String[] translation) {
this.translation = translation;
}
public mBasic getBasic() {
return basic;
}
public void setBasic(mBasic basic) {
this.basic = basic;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
public class mBasic {
private String phonetic;
private String[] explains;
public String getPhonetic() {
return phonetic;
}
public void setPhonetic(String phonetic) {
this.phonetic = phonetic;
}
public String[] getExplains() {
return explains;
}
public void setExplains(String[] explains) {
this.explains = explains;
}
}
}
}
}
下面这个是把json字符串转换为java对象
package youdao.yf.com;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Administrator on 2016/2/19.
*/
//此地址https://www.juhe.cn/有这个类,
public class JuheDemo {
public static final String DEF_CHATSET = "UTF-8";
public static final int DEF_CONN_TIMEOUT = 30000;
public static final int DEF_READ_TIMEOUT = 30000;
public static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
//申请的KEY 这是APPKEY需要你们自己去聚合申请
public static final String APPKEY="";
//有道翻译,此类型本来为void ,改为java对象
public static YouDaoBean getRequest1(String word){
String result=null;
String url=http://japi.juhe.cn/youdao/dictionary.from;
Map<String,Object>params=new HashMap<String,Object>();
params.put("key",APPKEY);
//搜索的字符
params.put("word",word);
//默认都要搜索出来
params.put("only","");
try {
//json字符
result=net(url,params,"GET");
Gson gson=new Gson();
//获取类型的泛型类作为TypeToken的泛型参数构造一个匿名的子类,
// 就可以通过getType()方法获取到我们使用的泛型类的泛型参数类型
Type type=new TypeToken<YouDaoBean>() {
}.getType();
//json字符串转换为java对象
YouDaoBean jsonbean=gson.fromJson(result,type);
if(jsonbean.getResult().getData()==null){
return null;
}
return jsonbean;
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String net(String strUrl, Map<String, Object> params,String method) throws Exception {
HttpURLConnection conn = null;
BufferedReader reader = null;
String rs = null;
try {
StringBuffer sb = new StringBuffer();
if(method==null || method.equals("GET")){
//此时strUrl为http://japi.juhe.cn/youdao/dictionary.from?word=&only=&key=,完整的请求地址
strUrl = strUrl+"?"+urlencode(params);
}
URL url = new URL(strUrl);
conn = (HttpURLConnection) url.openConnection();
//判断是GET请求,还有POST请求,设置请求方式
// 如果是POST请求,参数要放在http正文内,因此setDoOutput为true
// 一般默认为false,
if(method==null || method.equals("GET")){
conn.setRequestMethod("GET");
}else{
conn.setRequestMethod("POST");
conn.setDoOutput(true);
}
///设定传送的内容类型是可序列化的java对象
// (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
conn.setRequestProperty("User-agent", userAgent);
//POST请求不能缓存
conn.setUseCaches(false);
conn.setConnectTimeout(DEF_CONN_TIMEOUT);
conn.setReadTimeout(DEF_READ_TIMEOUT);
conn.setInstanceFollowRedirects(false);
conn.connect();
if (params!= null && method.equals("POST")) {
try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) {
out.writeBytes(urlencode(params));
}
}
InputStream is = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sb.append(strRead);
}
rs = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
if (conn != null) {
conn.disconnect();
}
}
return rs;
}
public static String urlencode(Map<String,?>data){
StringBuffer sb=new StringBuffer();
for(Map.Entry<String,?>i:data.entrySet()){
try {
//请求地址的拼接 转换为UTF-8
sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
//最后拼接成word=&only=&key=,等号后面是i.getValue
return sb.toString();
}
}
下面是具体怎么实现
package youdao.yf.com;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import json.yf.com.jsongson.R;
import static android.widget.Toast.LENGTH_LONG;
/**
* Created by Administrator on 2016/2/21.
*/
public class YouDaoActivity extends Activity implements View.OnClickListener {
private Button btn;
private EditText et_search;
private TextView tv_view1;
private TextView tv_view2;
public String str ;
public String string = "";//此string是用来存储上一个搜索的字符的数据;
MyHandler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.youdao_main);
btn= (Button) findViewById(R.id.btn);
et_search= (EditText) findViewById(R.id.et_search);
tv_view1= (TextView) findViewById(R.id.tv_view1);
tv_view2= (TextView) findViewById(R.id.tv_view2);
//实例化一个Handler
handler=new MyHandler();
btn.setOnClickListener(this);
}
@Override
public void onClick(View view) {
//点击按钮,开始线程
//因为主线程不能加载网络,用子线程请求网络
new Youdao().start();
}
//线程
class Youdao extends Thread{
@Override
public void run() {
str = et_search.getText().toString();
Message message = new Message();
//str为非空
if(!str.equals("")) {
System.out.println(str);
//获取网络上的json,再转换为Java对象
YouDaoBean bean = JuheDemo.getRequest1(str);
//判断data对象是否为空
if (bean.getResult().getData() != null) {
//如果为第一次搜索,此string为空,而str不为空。
//如果是第二次或者多次,此string为上一次搜索的字符,而str本次搜索的
//字符,相同为已经查出,不通更换数据;
if (string.equals(str)) {
System.out.println("已查询");
message.what=2;
handler.sendMessage(message);
} else {
message.obj = bean;
message.what = 1;
System.out.println(bean.getResult().getData().getTranslation()[0]);
string = str;
handler.sendMessage(message);
}
}
}
else{
System.out.println("输入为空");
message.what=0;
handler.sendMessage(message);
}
}
}
//定义的handler
class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//根据msg.what判断情况
//what==0,输入框为空,搜索
//what==1,成功获取josn对象,并且获取到data对象
//what==2,上一次查询字符与本次查询字符相同,表现已查询
if(msg.what==0){
Toast.makeText(YouDaoActivity.this,"输入为空", LENGTH_LONG).show();
}
else if(msg.obj!=null&&msg.what==1){
//获取线程传过来的对象
YouDaoBean bean = (YouDaoBean) msg.obj;
String stringone=bean.getResult().getData().getTranslation()[0];
String[] stringtwo=bean.getResult().getData().getBasic().getExplains();
StringBuilder sb=new StringBuilder();
for(int i=0;i<stringtwo.length;i++){
sb.append(stringtwo[i]).append("\r\n");
}
tv_view1.setText(stringone);
tv_view2.setText(sb);
}
else if(msg.what==2){
Toast.makeText(YouDaoActivity.this,"已查询", LENGTH_LONG).show();
}
}
}
}
然后是布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/et_search"
android:layout_width="0dp"
android:layout_weight="2"
android:layout_height="wrap_content" />
<Button
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="搜索"
android:id="@+id/btn" />
</LinearLayout>
<TextView
android:id="@+id/tv_view1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="23sp"
android:padding="10dp"
/>
<TextView
android:textSize="23sp"
android:id="@+id/tv_view2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"/>
</LinearLayout>
就这样,android获取多层的json就完了,本人还是新手,只是边学习边写博客,不但可以与人分享,自己还可以回头在看看,
第一次写博客,还有很多方面没有考虑到,还希望高手多多指点,我的农码之路,才刚刚启程,在路上,望大家多多给链接,图片和代码。