Android 解析Json (demo)
以下是个小demo: 效果图在下面:
可以在云盘下载原代码:http://pan.baidu.com/s/1c14qPGG
–首先要在服务端生成Json
–生成Json要在 Eclipse 里编写(用的是SSH框架)
–Jsp代码: getData.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<a href="/front/fqAction.xhtml">获取XML数据</a><br/>
<a href="/front/JsonAction.xhtml">获取Json数据</a>
</body>
</html>
-然后编写实体类:
package com.zking.entity;
public class FQ {
private String name;
private String content;
private String time;
public FQ() {
super();
// TODO Auto-generated constructor stub
}
public FQ(String name, String content, String time) {
super();
this.name = name;
this.content = content;
this.time = time;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
在Action里新建一个FQAction.Java:
package com.zking.action;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.ActionSupport;
import com.zking.entity.FQ;
@Controller
public class FQAction {
@RequestMapping(value="/front/fqAction.xhtml")
public String getXML(HttpServletRequest req) throws Exception {
// 获取数据
// 调用数据库查询数据,返回对象集合(....)
List<FQ> fqs = new ArrayList<FQ>();
for (int i = 1; i <= 10; i++) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
fqs.add(new FQ("pull" + i, "今天心情很nice", year + "-" + month + "-" + day));
}
// 将对象集合存放到请求域中
req.setAttribute("fqs", fqs);
return "dataResult";
}
@RequestMapping(value="/front/JsonAction.xhtml")
public String getJson(HttpServletRequest req) throws Exception {
// 获取数据
// 调用数据库查询数据,返回对象集合(....)
List<FQ> fqs = new ArrayList<FQ>();
for (int i = 1; i <= 10; i++) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
fqs.add(new FQ("Json+pull" + i, "今天心情很nice", year + "-" + month + "-" + day));
}
// {}对象 JsonObject
// []集合 JsonArray
//将对象集合转换成Json
JSONObject json=new JSONObject();
json.put("clazz", "9990");
json.put("lists", fqs.size());
JSONArray jsona=new JSONArray();
for (FQ fq : fqs) {
JSONObject object=new JSONObject();
object.put("name", fq.getName());
object.put("content", fq.getContent());
object.put("time", fq.getTime());
jsona.add(object);
}
json.put("fqs", jsona);
// 将对象集合存放到请求域中
req.setAttribute("fqs", json.toString());
return "dataResultJson";
}
}
然后新建一个JSP dataResultJson.jsp
注:注意格式
<%@ page language="java" contentType="text/plain; charset=utf-8"
pageEncoding="utf-8"%>${fqs }
编写完成可以运行下
效果如:
注: 这个路径 http://localhost:8090/front/JsonAction.xhtml 的localhost要改成你的网络IP地址
接下来要获取网络Json数据 (在Android Studio里编写)
-首先要先在清单文件下配置网络权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dzz.android30_sax_xml">
<!-- 网络权限 -->
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
</activity>
<activity android:name=".JsonActivity"> <intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter></activity>
</application>
</manifest>
-然后编写XML —activity_json.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_json"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.dzz.android30_sax_xml.JsonActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="getJson"
android:text="获取Json" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/lv_json"
>
</ListView>
</LinearLayout>
-然后获取网络数据 JsonActivity
package com.dzz.android30_sax_xml;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class JsonActivity extends AppCompatActivity {
private List<FQ> lists = new ArrayList<>();
private ListView lv_json;
private MyAdapter myAdapter;
private ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_json);
lv_json = (ListView) findViewById(R.id.lv_json);
//适配器
myAdapter = new MyAdapter();
lv_json.setAdapter(myAdapter);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("正在加载。。。");
}
//适配器
class MyAdapter extends BaseAdapter {
@Override
public int getCount() {
return lists.size();
}
@Override
public Object getItem(int i) {
return lists.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
view = LayoutInflater.from(JsonActivity.this).inflate(R.layout.item_listview, null);
ItemTag itemTag = new ItemTag();
itemTag.tv_content = (TextView) view.findViewById(R.id.lv_b);
itemTag.tv_name = (TextView) view.findViewById(R.id.lv_a);
itemTag.tv_time = (TextView) view.findViewById(R.id.lv_c);
view.setTag(itemTag);
}
ItemTag itemTag = (ItemTag) view.getTag();
itemTag.tv_name.setText(lists.get(i).getName());
itemTag.tv_content.setText(lists.get(i).getContent());
itemTag.tv_time.setText(lists.get(i).getTime());
return view;
}
}
public void getJson(View view){
new MyTask().execute();
}
class MyTask extends AsyncTask{
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
@Override //数据
protected Object doInBackground(Object[] objects) {
//这个路径 http://localhost:8090/front/fqAction.xhtml 在 values 的 strings.xml 下
//可以编写一个
//<resources>
// <string name="app_name">Android30_sax_xml</string>
// <string name="server_name">http://172.20.10.3:8090</string>
//</resources>
//可以公用一个 如下:
String path=getString(R.string.server_name)+"/front/JsonAction.xhtml";
try {
URL url=new URL(path);
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
if(connection.getResponseCode()==200){
InputStream is=connection.getInputStream();
//读
BufferedReader br=new BufferedReader(new InputStreamReader(is));
StringBuffer stringBuffer=new StringBuffer();
String str=null;
while ((str=br.readLine())!=null){
stringBuffer.append(str);
}
Log.i("test",stringBuffer.toString());
//解析 Json
// 1. 原生态
// try {
// JSONObject jsonObject=new JSONObject(stringBuffer.toString());
// String clazz= jsonObject.getString("class");
// Log.i("test","class:"+clazz);
// int num=jsonObject.getInt("lists");
// Log.i("test","lists:"+num);
// JSONArray jsonArray= jsonObject.getJSONArray("fqs");
// for (int i = 0; i < jsonArray.length(); i++) {
// JSONObject object= jsonArray.getJSONObject(i);
// String name=object.getString("name");
// String content=object.getString("content");
// String time=object.getString("time");
// FQ fq=new FQ(name,content,time);
// lists.add(fq);
// }
//
// } catch (JSONException e) {
// e.printStackTrace();
// }
//2. 使用Gson析Json
//使用 Gson 要导个JAR包 这个包要自己下载
//在Dependencies 里如图在下面:
// Gson gson=new Gson();
// BigFQ bigfq= gson.fromJson(stringBuffer.toString(),BigFQ.class);
//
// String clazz=bigfq.getClazz();
// int num=bigfq.getLists();
// Log.i("test","clazz:"+clazz+"==数量:"+num);
// lists.addAll(bigfq.getFqs());
//3. 使用FastJson
//要导一个JAR包在上面的网址里云盘
//把项目切换成Project 然后复制到项目的libs文件夹下面 然后右键add Ar Library编译下
BigFQ bigfq= JSON.parseObject(stringBuffer.toString(),BigFQ.class);
String clazz=bigfq.getClazz();
int num=bigfq.getLists();
Log.i("test","clazz:"+clazz+"==数量:"+num);
lists.addAll(bigfq.getFqs());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
myAdapter.notifyDataSetChanged(); //通知适配器发生改变
progressDialog.cancel();
}
}
}
Gson 导包图:
-在Activity 里新建 实体类 是要有的
package com.dzz.android30_sax_xml;
public class FQ {
private String name;
private String content;
private String time;
public FQ() {
super();
}
public FQ(String name, String content, String time) {
super();
this.name = name;
this.content = content;
this.time = time;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
还要在新建一个实体类 BigFQ
package com.dzz.android30_sax_xml;
import java.util.List;
/**
* Created by 朝花偏不夕拾 on 2017/2/25.
*/
public class BigFQ {
private String clazz;
private int lists;
private List<FQ> fqs;
public String getClazz() {
return clazz;
}
public void setClazz(String clazz) {
this.clazz = clazz;
}
public int getLists() {
return lists;
}
public void setLists(int lists) {
this.lists = lists;
}
public List<FQ> getFqs() {
return fqs;
}
public void setFqs(List<FQ> fqs) {
this.fqs = fqs;
}
public BigFQ() {
}
public BigFQ(String clazz, int lists, List<FQ> fqs) {
this.clazz = clazz;
this.lists = lists;
this.fqs = fqs;
}
}
-在Activity 里新建一个 ItemTag
package com.dzz.android30_sax_xml;
import android.widget.TextView;
/**
* Created by 朝花偏不夕拾 on 2017/2/24.
*/
public class ItemTag {
public TextView tv_name;
public TextView tv_content;
public TextView tv_time;
}
-还要新建一个布局文件 - item_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/lv_a" />
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/lv_b" />
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/lv_c" />
</LinearLayout>
以下是效果图: