Android之解析JSON数据示例(android原生态,FastJson,Gson)

1.json网页代码

<%@ page language="java" contentType="text/plain; charset=UTF-8"
 pageEncoding="UTF-8"%><%@page isELIgnored="false" %>${fqs }

2.json数据网页效果图

3.Android代码

布局

<?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_main"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical">

 <Button
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:text="获取JSON数据"
  android:onClick="getJSON"/>

 <ListView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:id="@+id/lv_json_main"></ListView>
</LinearLayout>

<?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_main_fastjson"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical">

 <Button
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:text="获取JSON数据fastjson"
  android:onClick="getFastjson"/>

 <ListView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:id="@+id/lv_fastjson_main"></ListView>
</LinearLayout>

<?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_main_gson"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical">

 <Button
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:text="获取JSON数据Gson"
  android:onClick="getGSON"/>

 <ListView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:id="@+id/lv_gson_main"></ListView>
</LinearLayout>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="horizontal">

 <TextView
  android:layout_width="0dp"
  android:layout_height="wrap_content"
  android:id="@+id/tv_item_listview_name"
  android:layout_weight="1"/>

 <TextView
  android:layout_width="0dp"
  android:layout_height="wrap_content"
  android:id="@+id/tv_item_listview_content"
  android:layout_weight="1"/>

 <TextView
  android:layout_width="0dp"
  android:layout_height="wrap_content"
  android:id="@+id/tv_item_listview_time"
  android:layout_weight="1"/>
</LinearLayout>

Android原生态代码解析

public class MainActivity extends AppCompatActivity {

 private ListView lv_json_main;
 private List<FQ> fqs = new ArrayList<>();
 private MyAdapter myadapter;
 private ProgressDialog progressDialog;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  lv_json_main = (ListView) findViewById(R.id.lv_json_main);
  myadapter = new MyAdapter();
  lv_json_main.setAdapter(myadapter);

  progressDialog = new ProgressDialog(this);
  progressDialog.setMessage("小青正在拼命加載中.....");
 }

 class MyAdapter extends BaseAdapter {

  @Override
  public int getCount() {
   return fqs.size();
  }

  @Override
  public Object getItem(int position) {
   return fqs.get(position);
  }

  @Override
  public long getItemId(int position) {
   return position;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
   if (convertView == null) {
    convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.item_list, null);
    ItemTag itemTag = new ItemTag();
    itemTag.tv_name = (TextView) convertView.findViewById(R.id.tv_item_listview_name);
    itemTag.tv_content = (TextView) convertView.findViewById(R.id.tv_item_listview_content);
    itemTag.tv_tiem = (TextView) convertView.findViewById(R.id.tv_item_listview_time);
    convertView.setTag(itemTag);
   }
   ItemTag itemTag = (ItemTag) convertView.getTag();
   itemTag.tv_name.setText(fqs.get(position).getName());
   itemTag.tv_content.setText(fqs.get(position).getContent());
   itemTag.tv_tiem.setText(fqs.get(position).getTime());

   return convertView;
  }
 }

 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[] params) {
   String path = "http://192.168.43.149:8080/datajson.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);
     }
     //使用原生态解析JSON数据
     JSONObject jsonObject=new JSONObject(stringBuffer.toString());
     String clazz=jsonObject.getString("clazz");
     int lists=jsonObject.getInt("lists");
     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);
      fqs.add(fq);
     }
    }
   } catch (Exception e) {
    e.printStackTrace();
   }
   return null;
  }

  //获取数据后更新UI
  @Override
  protected void onPostExecute(Object o) {
   super.onPostExecute(o);
   progressDialog.cancel();
   myadapter.notifyDataSetChanged();
  }
 }
}

使用Fastjson解析

public class MainFastjsonActivity extends AppCompatActivity {

 private ListView lv_fastjson_main;
 private List<FQ> fqs = new ArrayList<>();
 private MyAdapter myadapter;
 private ProgressDialog progressDialog;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main_fastjson);
  lv_fastjson_main = (ListView) findViewById(R.id.lv_fastjson_main);
  myadapter = new MyAdapter();
  lv_fastjson_main.setAdapter(myadapter);

  progressDialog = new ProgressDialog(this);
  progressDialog.setMessage("小青正在拼命加載中.....");
 }

 class MyAdapter extends BaseAdapter {

  @Override
  public int getCount() {
   return fqs.size();
  }

  @Override
  public Object getItem(int position) {
   return fqs.get(position);
  }

  @Override
  public long getItemId(int position) {
   return position;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
   if (convertView == null) {
    convertView = LayoutInflater.from(MainFastjsonActivity.this).inflate(R.layout.item_list, null);
    ItemTag itemTag = new ItemTag();
    itemTag.tv_name = (TextView) convertView.findViewById(R.id.tv_item_listview_name);
    itemTag.tv_content = (TextView) convertView.findViewById(R.id.tv_item_listview_content);
    itemTag.tv_tiem = (TextView) convertView.findViewById(R.id.tv_item_listview_time);
    convertView.setTag(itemTag);
   }
   ItemTag itemTag = (ItemTag) convertView.getTag();
   itemTag.tv_name.setText(fqs.get(position).getName());
   itemTag.tv_content.setText(fqs.get(position).getContent());
   itemTag.tv_tiem.setText(fqs.get(position).getTime());

   return convertView;
  }
 }

 public void getFastjson(View view) {
  new Mytask().execute();
 }

 class Mytask extends AsyncTask {

  //获取数据前
  @Override
  protected void onPreExecute() {
   super.onPreExecute();
   progressDialog.show();
  }

  @Override
  protected Object doInBackground(Object[] params) {
   String path = "http://192.168.43.149:8080/datajson.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);
     }
     //使用FastJson解析JSON数据
     BigFQ bigFQ=JSON.parseObject(stringBuffer.toString(),BigFQ.class);
     String clazz=bigFQ.getClazz();
     int num=bigFQ.getLists();
     fqs.addAll(bigFQ.getFqs());
    }
   } catch (Exception e) {
    e.printStackTrace();
   }
   return null;
  }

  //获取数据后更新UI
  @Override
  protected void onPostExecute(Object o) {
   super.onPostExecute(o);
   progressDialog.cancel();
   myadapter.notifyDataSetChanged();
  }
 }
}

使用gson解析

public class MainGsonActivity extends AppCompatActivity {

 private ListView lv_gson_main;
 private List<FQ> fqs = new ArrayList<>();
 private MyAdapter myadapter;
 private ProgressDialog progressDialog;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main_gson);
  lv_gson_main = (ListView) findViewById(R.id.lv_gson_main);
  myadapter = new MyAdapter();
  lv_gson_main.setAdapter(myadapter);

  progressDialog = new ProgressDialog(this);
  progressDialog.setMessage("小青正在拼命加載中.....");
 }

 class MyAdapter extends BaseAdapter {

  @Override
  public int getCount() {
   return fqs.size();
  }

  @Override
  public Object getItem(int position) {
   return fqs.get(position);
  }

  @Override
  public long getItemId(int position) {
   return position;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
   if (convertView == null) {
    convertView = LayoutInflater.from(MainGsonActivity.this).inflate(R.layout.item_list, null);
    ItemTag itemTag = new ItemTag();
    itemTag.tv_name = (TextView) convertView.findViewById(R.id.tv_item_listview_name);
    itemTag.tv_content = (TextView) convertView.findViewById(R.id.tv_item_listview_content);
    itemTag.tv_tiem = (TextView) convertView.findViewById(R.id.tv_item_listview_time);
    convertView.setTag(itemTag);
   }
   ItemTag itemTag = (ItemTag) convertView.getTag();
   itemTag.tv_name.setText(fqs.get(position).getName());
   itemTag.tv_content.setText(fqs.get(position).getContent());
   itemTag.tv_tiem.setText(fqs.get(position).getTime());

   return convertView;
  }
 }

 public void getGSON(View view) {
  new Mytask().execute();
 }

 class Mytask extends AsyncTask {

  //获取数据前
  @Override
  protected void onPreExecute() {
   super.onPreExecute();
   progressDialog.show();
  }

  @Override
  protected Object doInBackground(Object[] params) {
   String path = "http://192.168.43.149:8080/datajson.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);
     }
     //使用Gson解析json数据
     Gson gson=new Gson();
     BigFQ bigFQ=gson.fromJson(stringBuffer.toString(),BigFQ.class);
     String clazz=bigFQ.getClazz();
     int num=bigFQ.getLists();
     fqs.addAll(bigFQ.getFqs());
     Log.i("哈哈","6");
    }
   } catch (Exception e) {
    e.printStackTrace();
   }
   return null;
  }

  //获取数据后更新UI
  @Override
  protected void onPostExecute(Object o) {
   super.onPostExecute(o);
   progressDialog.cancel();
   myadapter.notifyDataSetChanged();
  }
 }
}

实体类

public class BigFQ {
 private String clazz;
 private int lists;
 private List<FQ> fqs;

 public BigFQ() {
 }

 public BigFQ(String clazz, List<FQ> fqs, int lists) {
  this.clazz = clazz;
  this.fqs = fqs;
  this.lists = lists;
 }

 public String getClazz() {
  return clazz;
 }

 public void setClazz(String clazz) {
  this.clazz = clazz;
 }

 public List<FQ> getFqs() {
  return fqs;
 }

 public void setFqs(List<FQ> fqs) {
  this.fqs = fqs;
 }

 public int getLists() {
  return lists;
 }

 public void setLists(int lists) {
  this.lists = lists;
 }
}

public class FQ {
 private String name;
 private String content;
 private String time;

 public FQ(){}
 public FQ(String name, String time, String content) {
  this.name = name;
  this.time = time;
  this.content = content;
 }

 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;
 }
}

public class ItemTag {
 public TextView tv_name;
 public TextView tv_content;
 public TextView tv_tiem;
}

添加联网权限

 <!--添加联网权限-->
 <uses-permission android:name="android.permission.INTERNET" />

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Android 解析JSON对象及实例说明

    JSON是一种轻量级的对象,数据体积小,方便传输,易于解析! 首先新建一个类工具类JsonUtil,用于获取请求返回的数据 复制代码 代码如下: public class JsonUtil { private static final String TAG = "JSONUTIL"; public static JSONObject getJSON(String url) throws Exception {  return new JSONObject(getRequest(url)

  • Android webview与js交换JSON对象数据示例

    最近几个项目的测试结果,Android无法主动通过调用 webview.loadUrl("javascript:"+callbackFunction+"('"+data+"')"); 这种方式将jsonobject类型的data传给js,因为js那边得到就是一个string的对象. 与此同时,js主动调用android的对象方式,android也无法返回给js一个jsonobject,需要js做一下转换,例如: Android 代码: 复制代码

  • Android实现读写JSON数据的方法

    本文实例讲述了Android实现读写JSON数据的方法.分享给大家供大家参考.具体如下: 1. 解析JSON: package de.vogella.android.twitter.json; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpEntit

  • Android网络编程之获取网络上的Json数据实例

    为要获取网络上的Json所以需要服务器端提供的支持. 一.创建服务器端: 服务器端项目结构: 服务器端运行效果图: 第一步:创建业务所需的JavaBean 复制代码 代码如下: package com.jph.sj.model;   import java.util.Date;   /**  * 新闻实体类  * @author jph  * Date:2014.09.26  */ public class News {     private Integer id;     private S

  • Android App数据格式Json解析方法和常见问题

    (1).解析Object之一: 复制代码 代码如下: {"url":"http://www.cnblogs.com/qianxudetianxia"} 解析方法: 复制代码 代码如下: JSONObject demoJson = new JSONObject(jsonString);String url = demoJson.getString("url"); (2).解析Object之二: 复制代码 代码如下: {"name"

  • Android编程心得分享——JSON学习过程

    让我说说Android编程心得,在我们初步学习JSON时我们都知道JSON作为现在比较流行的数据交换格式,有着它的许多优点,Android的WEB应用中更是广泛用到了它,这里将我学习JSON的过程记录如下 在Android的Android.jar包中已经默认引入了这个包,这里我们就可以直接调用它了 JSON有五种基本类型,分别是object,array,value,string,number Object 以下面这个为例 {"person":{"id":100,&q

  • android 解析json数据格式的方法

    json数据格式解析我自己分为两种: 一种是普通的,一种是带有数组形式的: 普通形式的:服务器端返回的json数据格式如下: 复制代码 代码如下: {"userbean":{"Uid":"100196","Showname":"\u75af\u72c2\u7684\u7334\u5b50","Avtar":null,"State":1}} 分析代码如下: 复制代码 代

  • Android中Json数据读取与创建的方法

    首先介绍下JSON的定义,JSON是JavaScript Object Notation的缩写. 一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性.业内主流技术为其提供了完整的解决方案(有点类似于正则表达式,获得了当今大部分语言的支持),从而可以在不同平台间进行数据交换.JSON采用兼容性很高的文本格式,同时也具备类似于C语言体系的行为. JSON的结构: (1) Name/Value Pairs(无序的):类似所熟知的Keyed list. Hash table.Disctiona

  • Android中生成、使用Json数据实例

    1.Json的制作 复制代码 代码如下: package com.example.usingjson2;    import org.json.JSONException;  import org.json.JSONObject;    import android.os.Bundle;  import android.app.Activity;    public class MainActivity extends Activity {        @Override      prote

  • Android中的JSON详细总结

    1.JSON(JavaScript ObjectNotation) 定义: 一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性.业内主流技术为其提供了完整的解决方案(有点类似于正则表达式,获得了当今大部分语言的支持),从而可以在不同平台间进行数据交换.JSON采用兼容性很高的文本格式,同时也具备类似于C语言体系的行为. – Json.org 2.JSON的结构: (1) Name/Value Pairs(无序的):类似所熟知的Keyed list. Hash table.Disctio

随机推荐