1. 程式人生 > >android 之json物件解析並展示(含json解析原始碼)

android 之json物件解析並展示(含json解析原始碼)

具體處理思路以及使用到的知識點:

1.使用android的非同步處理

2.將要使用的功能(方法)進行封裝,以便主類進行呼叫

3.前臺展示要使用介面卡模型(這裡使用簡單介面卡(SimpleAdapter))

主類的程式碼:

package com.example.lenovo.asynctask_json;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.example.lenovo.asynctask_json.domin.NetUtils;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
/**
 * {}代表 json物件
 * []:代表時json 陣列
 *
 * {key:value,key:value,key:value.....}
 *
 * {
 *  name:"張三",
 *
 *  age:20,
 *
 *  tel:[111,222,333,444],
 *
 *  loves:[
 *      {ball:"球"},
 *      {game:"遊戲"}
 *
 *  ]
 *
 *  }
 */
public class MainActivity extends AppCompatActivity {
    private ListView listView_movie;
    private SimpleAdapter adapter;
    private List<Map<String,Object>> list;
    //private String  path="http://lib.wap.zol.com.cn/ipj/docList.php?class_id=0&page=1&vs=and380&retina=1
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.listView_movie= (ListView) this.findViewById(R.id.listView_movie);
        String  path= null;
        try {
            //URLEncoder.encode("熱門","utf-8"):將漢字進行Unicode編碼
            path = "https://movie.douban.com/j/search_subjects?type=movie&tag="+ URLEncoder.encode("熱門","utf-8")+"&sort=recommend&page_limit=20&page_start=21";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        new NetDownLoadAsyncTask().execute(path);
    }
    private final class NetDownLoadAsyncTask extends AsyncTask<String,Void,List<Map<String,Object>>>{
        @Override
        protected List<Map<String, Object>> doInBackground(String... params) {

            //呼叫NetUtils類的方法,將網址對應的資料以InputStream的形式返回.
            InputStream inputStream=NetUtils.getInputStreamByPath(params[0]);

            if(inputStream!=null){
                //呼叫NetUtils類的方法,將輸入流轉換成字串.
                String json=NetUtils.getStringByInputStream(inputStream);
                System.out.println("json="+json);

                if(json!=null){
                    //呼叫NetUtils類的方法,對json物件進行處理
                    list= NetUtils.getListMapByJsonString(json);
                    return list;
                }
            }
            return null;
        }
        @Override
        protected void onPostExecute(List<Map<String, Object>> maps) {
            if(maps!=null){
                System.out.println("maps="+maps);
                adapter=new SimpleAdapter(
                        MainActivity.this,//上下文物件
                        maps,//資料來源
                        R.layout.movie_item,//前臺要展示的,這裡是(自己定義到格式)對應點選條目的樣式
                        new String[]{"title","cover"},//鍵值"title"與"cover"
             
                        new int[]{R.id.textView_title,R.id.imageView_cover}//控制元件對應id的int型陣列
                ){
                    /**
                     * 當每繪製一條條目物件時自動呼叫的方法
                     * @param position
                     * @param convertView
                     * @param parent
                     * @return
                     */
                    @Override
                    public View getView(int position, View convertView, ViewGroup parent) {
                        //System.out.println("===getView(int position="+position+", View convertView="+convertView+", ViewGroup parent="+parent+")===");
                        //得到當前繪製的條目物件
                        View view=super.getView(position, convertView, parent);
                        //System.out.println("view="+view);
                        ImageView imageView_cover= (ImageView) view.findViewById(R.id.imageView_cover);
                        Map<String,Object> map=list.get(position);
                        Bitmap bitmap= (Bitmap) map.get("cover");
                        //手工設定imageView對應的bitmap物件
                        imageView_cover.setImageBitmap(bitmap);
                        return view;
                    }
                };
                listView_movie.setAdapter(adapter);
                System.out.println("=======");
            }else {
                System.out.println("從網路上獲取資料失敗!");
            }
        }
    }
}

封裝好的程式碼:

package com.example.lenovo.asynctask_json.domin;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hsjwcf on 2018/5/29.
 */
public class NetUtils {

    /**
     * 將給你的網址對應的資料以InputStream的形式返回
     * @param path
     * @return
     */
    public static InputStream getInputStreamByPath(String path){
        try {
            URL url=new URL(path);
            HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(3000);

            /*
            httpURLConnection.getResponseCode()幹了兩件事:
            A:根據指定的網址向伺服器傳送請求並得到伺服器的迴應
            B:在迴應中包含狀態碼:200表示訪問成功

             */
            int responseCode=httpURLConnection.getResponseCode();
            if(responseCode==200){//說明本次訪問成功
                //以輸入流的形式得到伺服器返回的資料
                InputStream inputStream=httpURLConnection.getInputStream();
                return inputStream;

            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 根據輸入流得到位元組陣列
     * @param inputStream
     * @return
     */
    public static byte[]  getBytesByInputStream(InputStream inputStream){
        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        byte[] buffer=new byte[1024];
        int len=0;

        try {
            while ((len=inputStream.read(buffer))!=-1){
                byteArrayOutputStream.write(buffer,0,len);
            }

            return  byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 根據輸入流得到字串
     * @param inputStream
     * @return
     */
    public static String getStringByInputStream(InputStream inputStream){
        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        byte[] buffer=new byte[1024];
        int len=0;

        try {
            while ((len=inputStream.read(buffer))!=-1){
                byteArrayOutputStream.write(buffer,0,len);
            }

            return  byteArrayOutputStream.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 通過解析json 字串得到List<Map<String,Object>>型別的物件
     *
     *
     * {
     "subjects": [
     {
     "rate": "8.3",
     "cover_x": 3578,
     "title": "暴裂無聲",
     "url": "https://movie.douban.com/subject/26647117/",
     "playable": true,
     "cover": "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2517333671.jpg",
     "id": "26647117",
     "cover_y": 5078,
     "is_new": false
     },

     {
     "rate": "7.0",
     "cover_x": 1500,
     "title": "負重前行",
     "url": "https://movie.douban.com/subject/26793157/",
     "playable": false,
     "cover": "https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2518648419.jpg",
     "id": "26793157",
     "cover_y": 2222,
     "is_new": false
     }
     ]
     }

     * @param json
     * @return
     */
    public static List<Map<String,Object>> getListMapByJsonString(String json){

        List<Map<String,Object>> list=new ArrayList<>();

        try {
            //1.將json 字串轉換成Json物件
            JSONObject jsonObject=new JSONObject(json);

            //2.根據鍵得到json 陣列
            JSONArray jsonArray=jsonObject.getJSONArray("subjects");
            //得到陣列中元素的個數
            int len=jsonArray.length();
            for(int i=0;i<len;i++){
                Map<String,Object> map=new HashMap<>();
                jsonObject= jsonArray.getJSONObject(i);
                String title=jsonObject.getString("title");
                String cover=jsonObject.getString("cover");

                System.out.println("cover="+cover);
                //String cover=jsonArray.getString(0);



                map.put("title",title);
                //將資料來源中cover 對應的網址轉換成Bitmap 物件
                InputStream inputStream=getInputStreamByPath(cover);
                byte[] data=getBytesByInputStream(inputStream);
                Bitmap bitmap=BitmapFactory.decodeByteArray(data,0,data.length);

                map.put("cover",bitmap);

                list.add(map);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }
}

前臺展示:

<1>

<?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">

    <ImageView
        android:layout_gravity="center_horizontal"
        android:id="@+id/imageView_cover"
        android:layout_width="200dp"
        android:layout_height="200dp"
        />
    <TextView
        android:layout_gravity="center_horizontal"
        android:textSize="30sp"
        android:id="@+id/textView_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</LinearLayout>

<2>

<?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">
    <ListView
        android:id="@+id/listView_movie"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</LinearLayout>

相關推薦

android json物件解析展示(json解析原始碼)

具體處理思路以及使用到的知識點:1.使用android的非同步處理2.將要使用的功能(方法)進行封裝,以便主類進行呼叫3.前臺展示要使用介面卡模型(這裡使用簡單介面卡(SimpleAdapter))主類的程式碼:package com.example.lenovo.async

使用nodejs解析xlsx、csv檔案轉換成JSON檔案詳細教程(解決解析xlsx、csv檔案解析中文亂碼問題)

前言 最近工作中需要,領導給我一個csv檔案,讓我轉為JSON格式的檔案,決定使用nodejs來搞定,個人覺得這是用過的最簡單的方式;即使你沒用過node也可以通過本教程完成實現。你可能沒見過比這再詳細的教程文章了。可以收藏、轉載(轉載註明出處即可,不用與本人聯絡,大家分享學習,共同進步

用fastjson將物件的列表轉換成json格式,讀寫.json檔案

import com.alibaba.fastjson.JSON; import org.json.JSONArray; import org.json.JSONObject; public static void main(String[] args) {

Android呼叫系統照相機裁剪

Android呼叫系統照相機、相片並裁剪圖片並不是很難,網上也有很多資料,但是在實現的過程中我還是遇到了一些問題,現在做個總結。 一、 宣告系統許可權 因為呼叫的是系統照相機並且需要對sd卡進行讀寫操作所以需要用的的許可權有: //請求訪問使用照

AndroidMediaPlayer播放音樂實現進度條例項

首先,說明我們是從sd卡里讀檔案,來播放檔案!! 1、效果圖: 提前工作,往sd卡里放音樂檔案,如圖: 2、佈局檔案main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns

AndroidGson時間格式不一致導致後臺解析錯誤問題

採用Gson封裝Json資料與後臺進行互動,Android端與後臺介面通常對資料中的Date格式需要做統一處理,這樣就能保證Gson正常解析。但在不同的jdk版本的環境中,這樣處理也不能百分百保證沒有

fastjson-1.2.21 使用例項,複雜巢狀Java物件json物件,複雜巢狀json物件轉對應Java物件的程式碼實現

理論我就不多廢話了,直接看程式碼吧。使用的是fastjson-1.2.21版本的來實現下面程式碼的。 主要是實現複雜的巢狀的Java物件,也就是物件巢狀物件的複雜物件,轉換成json字串。然後就是反過來,把複雜的json字串轉換成對應的巢狀的Java物件。 先上工具類。如下

Java傳送POST請求,引數為JSON格式,接收返回JSON資料

/** * 傳送post請求 * @param url 路徑 * @param jsonObject 引數(json型別) * @param encoding 編碼格式 * @return * @throws P

Android訪問網路系列--服務端返回XML或JSON格式資料,Android 進行解析顯示

例子說明:使用者通過訪問web資源的最新電影資訊,伺服器端生成XML或JSON格式資料,返回Android客戶端進行顯示。 此案例開發需要兩個方面 WEB開發和android開發. 一.web開發相對比較簡單,只是模擬一下 相關程式碼如下: 1.實體Bean package ygc.yxb.domain

java呼叫http介面解析返回的json物件

import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import jav

Android解析Json陣列

在ListView顯示資料庫裡所有資料的時候,因為資料庫的資料是一條一條的記錄,在後臺返回的時候,我們往往是返回Json陣列的形式,把每一條資料當作是一個數組元素儲存起來。 先看下我們準備的Json陣列: [{ "id": "37", "bianhao": "201872986329

JavaScript格式化輸出展示Json物件

效果就是下面這樣子,開始還以為程式碼很複雜,實際上一句JSON.stringify(data, null, "\t")就解決了。 具體程式碼如下: <!DOCTYPE html> <html lang="en"> <head> <m

androidJSON解析

Json解析 JavaScrip物件表示法(JavaScript Object Notation)JSON屬於輕量級文字資料交換格式 JSon獨立於平臺和語言JSON具有自我描述性更易於理解 類似Xml,比Xml更小,更快,更易解析 Json檔案

Android-解析JSON資料(JSON物件/JSON陣列)

在上一篇部落格中,Android-封裝JSON資料(JSON物件/JSON陣列),講解到Android真實開發中更多的是去解析JSON資料(JSON物件/JSON陣列)   封裝JSON的資料是在伺服器端進行封裝了,Android更多的工作是解析(JSON物件/JSON陣列),所以Android

Android-Gson解析JSON資料(JSON物件/JSON陣列)

上一篇部落格,Android-解析JSON資料(JSON物件/JSON陣列),介紹了使用 org.json.JSONArray;/org.json.JSONObject; 來解析JSON資料;   Google Android 還提供來另外一種方式來解析JSON資料,那就是Gson;

Android獲取assets資料夾下的json資料,Gson解析!

Json 資料如下{ "code": 200, "msg": "ok", "news": [ { "title": "空降美國的孩子", "content": "在壓力和青春期的情緒波動

Android使用GSON解析JSON資料

GSON簡介: GSON是Google提供的用來在Java物件和JSON資料之間進行對映的Java類庫。GSON可以很容易的將一串JSON資料轉換為一個Java物件,或是將 一個Java物件轉換為相應的JSON資料。 使用GSON解析JSON資料的基本

servlet物件通過json返回到前臺頁面展示

1、實體類 import java.util.ArrayList; public class ObjectType { private String type; private ArrayList<SubObjectType> subObjects;

Android非同步任務AsyncTask解析Json資料

一、伺服器端 生成json資料 ①在eclipse中建立Web->Dynamic web Project 工程名命為Web_AsyncTask_Json。 ②建立CityAction.java類(Servlet類)。此時會出錯,原因是servlet-api.jar沒有

Android 解析json物件,存放到List中

比如解析這段從伺服器端返回的json字串: [{"Money":3,"EtcOutTime":"2017-5-20 15:30:22","CarId":0,"EtcInTime":"2017-5-20