解析json如同解析xml一样,步骤差不多,详情可以看我上一篇解析xml的步骤,这里是在生成json中有不同,这里列举了原生态,gson,FastJson三种方式:
依旧首先是在eclipse中生成json
首先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="studentActiongetJson.action">获取json数据</a>
</body>
</html>
接下来是有个student的实体类
private String name;
private String sex;
然后在StudentAction中写一个方法
public String getJson() throws Exception {
//查询数据库,得到数据
List<Student> students=new ArrayList<>();
for (int i = 0; i <=20; i++) {
Student student=new Student("娜娜", "女"+i);
students.add(student);
}
JSONObject jsonObject=new JSONObject();
jsonObject.put("clazz", "150825");
jsonObject.put("num", students.size());
JSONArray jsonArray=new JSONArray();
for (Student s : students) {
JSONObject jsonObject2=new JSONObject();
jsonObject2.put("name", s.getName());
jsonObject2.put("sex", s.getSex());
jsonArray.add(jsonObject2);
}
jsonObject.put("students", jsonArray);
//将对象集合保存到请求域中
ServletActionContext.getRequest().setAttribute("students", jsonObject.toString());
return "dataResultjson";
}
在Struts.xml中
<action name="studentAction*" class="com.zking.action.StudentAction" method="{1}">
<result name="dataResultjson">dataResultjson.jsp</result>
</action>
最后生成jsondata
Resultjson.jsp
<%@ page language="java" contentType="text/plain; charset=UTF-8"
pageEncoding="UTF-8"%>${students}
接下来是在Androidstudio中进行解析,和解析xml步骤相似
activity_main.xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="获取Json"
android:onClick="getJson"
/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/lv_main_list"
></ListView>
这里为了获取IP地址方便,可以在
strings.xml中
<resources>
<string name="app_name">parse_json</string>
<string name="server_name">http://192.168.43.109:8080/testssh/</string>
</resources>
这里需要两个实体类
BigStudent.java
package com.example.parse_json;
import java.util.List;
public class BigStudent {
private String clazz;
private int num;
private List<Student> students;
public BigStudent() {
}
public BigStudent(String clazz, int num, List<Student> students) {
this.clazz = clazz;
this.num = num;
this.students = students;
}
public String getClazz() {
return clazz;
}
public void setClazz(String clazz) {
this.clazz = clazz;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
}
student.java
package com.example.parse_json;
public class Student {
private String name;
private String sex;
public Student() {
super();
}
public Student(String name, String sex) {
super();
this.name = name;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
接下来是关键代码
ActivityMain.java
这里面有三种解析方式,原生态,gson,这一种方式在studio在加入gson的library便可,右击项目Open Moudle Setting
以及FastJson这是由阿里巴巴公司提供的,可以将这一jar放入项目的libs中
package com.example.parse_json;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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 MainActivity extends AppCompatActivity {
List<Student> studentList=new ArrayList<>();
private ListView lv_main_list;
private MyAdater myAdater;
private ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//添加listview
lv_main_list = (ListView) findViewById(R.id.lv_main_list);
//实例化适配器
myAdater = new MyAdater();
//设置适配器
lv_main_list.setAdapter(myAdater);
//实例化进度条对话框
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("json正在加载中.....");
}
class MyAdater extends BaseAdapter {
@Override
public int getCount() {
return studentList.size();
}
@Override
public Object getItem(int i) {
return studentList.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
LinearLayout layout=new LinearLayout(MainActivity.this);
layout.setOrientation(LinearLayout.HORIZONTAL);
TextView textViewName=new TextView(MainActivity.this);
textViewName.setText(studentList.get(i).getName());
TextView textViewsex=new TextView(MainActivity.this);
textViewsex.setText(studentList.get(i).getSex());
layout.addView(textViewName);
layout.addView(textViewsex);
return layout;
}
}
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) {
String path=getString(R.string.server_name)+"studentActiongetJson.action";
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();
StringBuffer sb=new StringBuffer();
String str=null;
BufferedReader br=new BufferedReader(new InputStreamReader(is));
while ((str=br.readLine())!=null){
sb.append(str);
}
// Log.i("test",sb.toString());
// Log.i("test","ff");
//原生态
// try {
// JSONObject jsonObject=new JSONObject(sb.toString());
// String clazz=jsonObject.getString("clazz");
// Log.i("test","clazz"+clazz);
// int num=jsonObject.getInt("num");
// Log.i("test","1111num"+num);
// JSONArray jsonArray= jsonObject.getJSONArray("students");
//
// for(int i=0;i<jsonArray.length();i++){
// JSONObject o= (JSONObject) jsonArray.getJSONObject(i);
// String name= o.getString("name");
// String sex= o.getString("sex");
// Log.i("test",name+""+sex);
//
// }
//
// } catch (JSONException e) {
// e.printStackTrace();
// }
//0.2使用Gson解析json
// Gson gson=new Gson();
// BigStudent b= gson.fromJson(sb.toString(),BigStudent.class);
// String clazz= b.getClazz();
// int num=b.getNum();
// Log.i("test","1111num"+num+"clazz:"+clazz);
// List<Student> students= b.getStudents();
// for (Student student : students) {
// Log.i("test",student.getName()+" "+student.getSex());
// }
//03.FastJson
BigStudent bigStudent=JSON.parseObject(sb.toString(),BigStudent.class);
String clazz=bigStudent.getClazz();
int num=bigStudent.getNum();
Log.i("test","aaaaaanum:"+num+" clazz:"+clazz);
List<Student> students=bigStudent.getStudents();
for (Student student : students) {
Log.i("test",student.getName()+" "+student.getSex());
studentList.add(student);
}
br.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
//通知适配器发生改变
myAdater.notifyDataSetChanged();
progressDialog.cancel();
}
}
}
最后依然是加入清单权限
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
在我上一篇中有解析xml的步骤,可以去看看