【Android 應用】gson數據解析實例

最近老是碰到json數據解析,記錄個實例以後方便參考。網上參考的例子基本沒有很全的json數據描述,記錄三個個實例更直觀的參考。

實例1:簡單json

解析下面json數據:

{
    ret : 0,
    sources : [
        {
            "name":"愛奇藝",
            "source":"iqiyi",
            "logo":"http://192.168.15.165:80/oms-pic/webSource/aiqiyi.png",
            "payInfo":"0","webPage":"https://v.qq.com/x/cover/io51j0gxgd2f5k3.html"
        }
    ],
    retInfo :"成功",
}

對應class:

public class WebH5UrlBean {
    /**
     * ret : 0
     * sources : [{"name":"愛奇藝","source":"iqiyi","logo":"http://192.168.15.165:80/oms-pic/webSource/aiqiyi.png","payInfo":"0","webPage":"https://v.qq.com/x/cover/io51j0gxgd2f5k3.html"}]
     * retInfo :
     */

    private String ret;
    private String retInfo;
    private List<SourcesBean> sources;

    public String getRet() {
        return ret;
    }

    public void setRet(String ret) {
        this.ret = ret;
    }

    public String getRetInfo() {
        return retInfo;
    }

    public void setRetInfo(String retInfo) {
        this.retInfo = retInfo;
    }

    public List<SourcesBean> getSources() {
        return sources;
    }

    public void setSources(List<SourcesBean> sources) {
        this.sources = sources;
    }

    public static class SourcesBean {
        /**
         * name : 愛奇藝
         * source : iqiyi
         * logo : http://192.168.15.165:80/oms-pic/webSource/aiqiyi.png
         * payInfo : 0
         * webPage : https://v.qq.com/x/cover/io51j0gxgd2f5k3.html
         */

        private String name;
        private String source;
        private String logo;
        private String payInfo;
        private String webPage;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getSource() {
            return source;
        }

        public void setSource(String source) {
            this.source = source;
        }

        public String getLogo() {
            return logo;
        }

        public void setLogo(String logo) {
            this.logo = logo;
        }

        public String getPayInfo() {
            return payInfo;
        }

        public void setPayInfo(String payInfo) {
            this.payInfo = payInfo;
        }

        public String getWebPage() {
            return webPage;
        }

        public void setWebPage(String webPage) {
            this.webPage = webPage;
        }
    }
}

解析代碼:

try {
    LogUtil.d(TAG, "getWebUrl response:" + response);
    String[] playUrls = {};
    int type = 0;
    Gson gson = new Gson();
    WebH5UrlBean paramInfo = gson.fromJson(response, WebH5UrlBean.class);
    if (paramInfo != null && paramInfo.getRet().equals("0")) {

        if (paramInfo.getSources() != null && paramInfo.getSources().size() > 0) {
            playUrls = new String[paramInfo.getSources().size()];
            for (int i = 0; i < paramInfo.getSources().size(); i++) {
                playUrls[i] = paramInfo.getSources().get(i).getWebPage();
            }
        } else {
            type = -1;
        }
    } else {
        type = -1;
    }

    VOSSDKListener listener = (VOSSDKListener) vossdkListener;
    listener.onWebUrlResponse(type, playUrls);
} catch (Exception e) {
    e.printStackTrace();
}

實例2:複雜json

解析下面json數據:

{
    "ret": "0",
    "result": [
        {
            "eventID": "ou0DtlIPoCeU",
            "title": "第一個計劃",
            "notice": 0,
            "type": "pic",
            "weight": 100,
            "startTime": "20200630000000",
            "endTime": "20200930235959",
            "url": "",
            "path": "http://192.168.15.162/rem/template/zip/20200630163041/b9368198832046db9296933cde5e8864/haixinbootad05.zip",
            "index": "http://192.168.15.162/rem/template/20200630163041/haixinbootad05/index.html?devId=18:82:19:E4:D2:B3",
            "paramsInfo": "img=http://192.168.15.162/rem/material/WQCwLGWSvQDw/2020/06/30/A4wx7L8znoIb.jpg&imgSmall=http://192.168.15.162/rem/material/WQCwLGWSvQDw/2020/06/30/HuW0k4lbhS2U.jpg&content=哈哈&detailUrl=",
            "src": null,
            "content": {
                "win_notice_url": [
                    "www.click1.com",
                    "www.click2.com",
                    "www.click3.com"
                ],
                "monitor_url": [
                    "https://imp.voiceads.cn/a/impress?impressId=35e9d12c-c3eb- 4565-83a0-1751a78c8cd2- 1587790905954&traceId=null&inAId=46388&wPltId=131&wPltAdId=3300098EE1A8D9A59B8ED EE59C7DB5E3&wPr=bT5tbICBmkUWUcbJVyZ0oQ&ua=__UA__&app=__APP__&aname=__ANAME_",
                    "https://ai.voiceads.cn/view?sid=45_3c26e507-179a-47d5-8aee- 482450bee85c_9af2bbf4-00f2-4946-a6a9- 1ac3c99669d4&info=CLmIj_UFEC0aACIAKNSf1m0wusY9ONjiuwFA9IF0SIrOkwFaIEUzRjU1MzZBMT QxODExREI0MEVGRDY0MDBGMUQwQTRFZQAAAABtAAAAAHABeICJeoABgIl6iAEBkgEyMzVlOWQxMmMtYz NlYi00NTY1LTgzYTAtMTc1MWE3OGM4Y2QyLTE1ODc3OTA5MDU5NTSYAZAcoAEAqgFDCAAQABgAIAAoAD ABOAZAaEg1UiN4Zl8zMzAwMDk4RUUxQThEOUE1OUI4RURFRTU5QzdEQjVFM1oHMzE5ODkwOGIBMA&wp= exFDgSMdGrASMYDDraZ9oA"
                ]
            },
            "planRate": 0,
            "planPeriod": 0,
            "mac": "18:82:19:E4:D2:B3",
            "planIpMacs": 0,
            "ip": "172.30.15.75"
        }
    ],
    "retInfo": "成功"
}

對應class:

public class AdContentInfo {
    private String ret;
    private String retInfo;
    private List<ResultBean> result;

	public String getRet() {
        return ret;
    }

    public void setRet(String ret) {
        this.ret = ret;
    }

    public String getRetInfo() {
        return retInfo;
    }

    public void setRetInfo(String retInfo) {
        this.retInfo = retInfo;
    }

    public List<ResultBean> getResult() {
        return result;
    }

    public void setResult(List<ResultBean> result) {
        this.result = result;
    }

	public static class ResultBean {
        /*
     	"eventID": "ou0DtlIPoCeU",
        "title": "第一個計劃",
        "notice": 0,
        "type": "pic",
        "weight": 100,
        "startTime": "20200630000000",
        "endTime": "20200930235959",
        "url": "",
        "path": "http://192.168.15.162/rem/template/zip/20200630163041/b9368198832046db9296933cde5e8864/haixinbootad05.zip",
        "index": "http://192.168.15.162/rem/template/20200630163041/haixinbootad05/index.html?devId=18:82:19:E4:D2:B3",
        "paramsInfo": "img=http://192.168.15.162/rem/material/WQCwLGWSvQDw/2020/06/30/A4wx7L8znoIb.jpg&imgSmall=http://192.168.15.162/rem/material/WQCwLGWSvQDw/2020/06/30/HuW0k4lbhS2U.jpg&content=哈哈&detailUrl=",
        "src": null,
        "content": {
            "win_notice_url": [
                "www.click1.com",
                "www.click2.com",
                "www.click3.com"
            ],
            "monitor_url": [
                "https://imp.voiceads.cn/a/impress?impressId=35e9d12c-c3eb- 4565-83a0-1751a78c8cd2- 1587790905954&traceId=null&inAId=46388&wPltId=131&wPltAdId=3300098EE1A8D9A59B8ED EE59C7DB5E3&wPr=bT5tbICBmkUWUcbJVyZ0oQ&ua=__UA__&app=__APP__&aname=__ANAME_",
                "https://ai.voiceads.cn/view?sid=45_3c26e507-179a-47d5-8aee- 482450bee85c_9af2bbf4-00f2-4946-a6a9- 1ac3c99669d4&info=CLmIj_UFEC0aACIAKNSf1m0wusY9ONjiuwFA9IF0SIrOkwFaIEUzRjU1MzZBMT QxODExREI0MEVGRDY0MDBGMUQwQTRFZQAAAABtAAAAAHABeICJeoABgIl6iAEBkgEyMzVlOWQxMmMtYz NlYi00NTY1LTgzYTAtMTc1MWE3OGM4Y2QyLTE1ODc3OTA5MDU5NTSYAZAcoAEAqgFDCAAQABgAIAAoAD ABOAZAaEg1UiN4Zl8zMzAwMDk4RUUxQThEOUE1OUI4RURFRTU5QzdEQjVFM1oHMzE5ODkwOGIBMA&wp= exFDgSMdGrASMYDDraZ9oA"
            ]
        },
        "planRate": 0,
        "planPeriod": 0,
        "mac": "18:82:19:E4:D2:B3",
        "planIpMacs": 0,
        "ip": "172.30.15.75"
         */

        private String eventID;
        private String title;
        private int notice;
        private String type;
        private int weight;
        private String startTime;
        private String endTime;
        private String url;
        private String path;
        private String index;
        private String paramsInfo;
        private String src;
		
    	private List<ContentBean> content;
		
        private int planRate;
        private int planPeriod;
        private String mac;
        private int planIpMacs;
        private String ip;

	    public String getParamsInfo() {
	        return paramsInfo;
	    }
    }

	public static class ContentBean {
		private List<String> win_notice_url;
		private List<String> monitor_url;
	}

}

解析代碼:

	private void getAdUrl(String iepgUrl, String mediaId, String devId) {
        try {
            Log.d(TAG, "AdClient getAdUrl mediaId:" + mediaId + ", devId:" + devId);

            if (iepgUrl != null && !iepgUrl.isEmpty()) {
                String requestUrl = iepgUrl;
                if (iepgUrl.endsWith("/")) {
                    requestUrl = iepgUrl + "adEventList?mediaId=" + mediaId + "&devId=" + devId;
                } else {
                    requestUrl = iepgUrl + "/adEventList?mediaId=" + mediaId + "&devId=" + devId;
                }
                Log.d(TAG, "AdClient getAdUrl requestUrl :" + requestUrl);

				OkHttpClient okHttpClient = new OkHttpClient();
	            Request request = new Request.Builder().url(requestUrl).build();
	            Log.d(TAG, "auth request: " + requestUrl);
	            Response response = okHttpClient.newCall(request).execute();
	            if (response.code() != 200){
	                Log.w(TAG, "auth return code." + response.code());
	                return ;
	            }

                try {
	            	String data = response.body().string();
                    Log.d(TAG, "getAdUrl response:" + data);
                    //Gson gson = new Gson();
                    //AdContentInfo adContentInfo = gson.fromJson(data, AdContentInfo.class);
					
		            Gson gson = new Gson();
		            Type type = new TypeToken<AdContentInfo>() {}.getType();
		            AdContentInfo adContentInfo = gson.fromJson(data, type);
                    if (adContentInfo != null && adContentInfo.getRet().equals("0")) {

                        if (adContentInfo.getResult() != null && adContentInfo.getResult().size() > 0) {
                            for (int i = 0; i < adContentInfo.getResult().size(); i++) {
                                ads[i] = adContentInfo.getResult().get(i).getParamsInfo();
                    			Log.d(TAG, "getAdUrl getParamsInfo:" + adContentInfo.getResult().get(i).getParamsInfo());
                            }
                        } else {
                    		Log.d(TAG, "getAdUrl getResult is null \n");
                        }
                    } else {
                    	Log.d(TAG, "getAdUrl adContentInfo is null \n");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                /*GetBuilder builder = OkHttpUtils.get()
                        .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0")
                        .url(requestUrl);

                final RequestCall build = builder.build();

                build.execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e1, int i) {
                        try {
                            String[] AdUrls = {};
                            Log.d(TAG, "getAdUrl onError");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onResponse(String response, int code) {
                        try {
                            Log.d(TAG, "getAdUrl response:" + response);
                            int type = 0;
                            Gson gson = new Gson();
                            AdContentInfo adContentInfo = gson.fromJson(response, AdContentInfo.class);
                            if (adContentInfo != null && paramInfo.getRet().equals("0")) {

                                if (adContentInfo.getResult() != null && adContentInfo.getResult().size() > 0) {
                                    for (int i = 0; i < paramInfo.getResult().size(); i++) {
                                        ads[i] = paramInfo.getResult().get(i).getParamsInfo();
                            			Log.d(TAG, "getAdUrl getParamsInfo:" + paramInfo.getResult().get(i).getParamsInfo());
                                    }
                                } else {
                            		Log.d(TAG, "getAdUrl getResult is null \n");
                                    type = -1;
                                }
                            } else {
                            	Log.d(TAG, "getAdUrl adContentInfo is null \n");
                                type = -1;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });*/
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

實例3:json文件解析

json文件:location.txt

{
"msg":"query success",
"code":"0",
"data":{
    "area":"",
    "country":"中國",
    "isp_id":"",
    "queryIp":"114.114.144.144",
    "city":"深圳市","ip":"114.114.144.144",
    "isp":"",
    "region_id":"440000",
    "county":"",
    "area_id":"",
    "county_id":"",
    "region":"廣東省",
    "country_id":"CN",
    "city_id":"440300"
    }
}

對應class:

 public static class LocalInfoBean
    {
        private String msg;
        private String code;
        private LocalDataBean data;

        public String getMsg()
        {
            return msg;
        }

        public void setMsg(String msg)
        {
            this.msg = msg;
        }

        public String getCode()
        {
            return code;
        }

        public void setCode(String code)
        {
            this.code = code;
        }

        public LocalDataBean getData()
        {
            return data;
        }

        public void setData(LocalDataBean data)
        {
            this.data = data;
        }
    }

    public static class LocalDataBean
    {
        private String area;
        private String country;
        private String isp_id;
        private String queryIp;
        private String city;
        private String ip;
        private String isp;
        private String region_id;
        private String county;
        private String area_id;
        private String county_id;
        private String region;
        private String country_id;
        private String city_id;

        public String getLocalInfoFromAdReport()
        {
            return "&areaId" + area_id + "&area" + area + "&regionId" + region_id + "&region" + region +
                   "&cityId" + city_id + "&city" + city + "&countyId" + county_id + "&county" + county;
        }
    }

解析代碼:

package com.seecool.apmservice.util;

import java.io.File;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import android.util.Log;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class LocalInfoUtils
{
    private final String TAG = "LocalInfoUtils";
    private static LocalInfoUtils singleton = null;
    private String CONF_FILE_PATH = "location.txt";
    private LocalInfoBean mLocalInfoBean = null;

    public synchronized static LocalInfoUtils getInstance()
    {
        if(null == singleton)
        {
            singleton = new LocalInfoUtils();
        }

        return singleton;
    }

    private LocalInfoUtils()
    {
        loadLocalInfo();
    }

    public LocalInfoBean getLocalInfo()
    {
        if(mLocalInfoBean == null){
            loadLocalInfo();
        }
        return mLocalInfoBean;
    }

    /**
    *加載地址信息
    */
    private synchronized void loadLocalInfo()
    {
        File in = new File(CONF_FILE_PATH);
        BufferedReader reader = null;

        try
        {
            StringBuffer stringBuffer = new StringBuffer();
            reader = new BufferedReader(new FileReader(in));
            String item = null;
            boolean sectionBegin = false;
            
            while ((item = reader.readLine()) != null) {
                stringBuffer.append(item);
            }
            
            String presonsString = stringBuffer.toString();
            Gson gson = new Gson();
            mLocalInfoBean = gson.fromJson(presonsString, LocalInfoBean.class);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (reader != null)
            {
                try
                {
                    reader.close();
                }
                catch (IOException e1)
                {
                }
            }
        }
    }

    /**
    *更新地址信息,暫時不做
    */
    public void updateLocalInfo(String config)
    {
        if (null == config)
        {
            return;
        }

        return ;
    }

    public static class LocalInfoBean
    {
        private String msg;
        private String code;
        private LocalDataBean data;

        public String getMsg()
        {
            return msg;
        }

        public void setMsg(String msg)
        {
            this.msg = msg;
        }

        public String getCode()
        {
            return code;
        }

        public void setCode(String code)
        {
            this.code = code;
        }

        public LocalDataBean getData()
        {
            return data;
        }

        public void setData(LocalDataBean data)
        {
            this.data = data;
        }
    }

    public static class LocalDataBean
    {
        private String area;
        private String country;
        private String isp_id;
        private String queryIp;
        private String city;
        private String ip;
        private String isp;
        private String region_id;
        private String county;
        private String area_id;
        private String county_id;
        private String region;
        private String country_id;
        private String city_id;

        public String getLocalInfoFromAdReport()
        {
            return "&areaId" + area_id + "&area" + area + "&regionId" + region_id + "&region" + region +
                   "&cityId" + city_id + "&city" + city + "&countyId" + county_id + "&county" + county;
        }
    }
}

結束語

比較簡單不做分析了,自行閱讀。有問題的話留言我。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章