android 如何解析复杂,包含中文key的json数据并进行展示

android 如何解析复杂,包含中文key的json数据

   通常在项目中,常常会有一些json数据包含中文key,而我们通常用AndroidStudio工具中的插件GsonFormat,使用这个插件将会自动生成实体Bean,然而总是有些后台的变态数据,例如包含中文的key,这时候我们就不能用GsonFormat工具了,我们就得用原始的JSONObject或者JSONArray了。

这里我用一个包含中文Key的Json数据来进行演示。

{
	"data": {
		"carArchive": {
			"2013-05上牌": "5年",
			"变速箱": "自动挡",
			"排放标准": "国三",
			"排放量": "2.3",
			"来源": "商家",
			"看车地点": "安次区",
			"表显里程": "2.0万公里",
			"车牌所在地": "廊坊",
			"过户次数": "1次过户"
		},
		"usedCar": {
			"brandName": "",
			"briefIntro": "2017年4月 2.0万公里 |2.3L 双离合",
			"carLocation": "安次区",
			"cardLocation": "廊坊",
			"constName": "",
			"deleteFlag": "0",
			"discharge": "国三",
			"emission": "2.3",
			"gearBox": "自动挡",
			"hotFiag": "0",
			"isLaunch": "1",
			"launchTime": "",
			"logoUrl": "https://www.dyhoa.com/mise/20180425/9d222f32-d51d-41b0-9005-5a21582483e7.png",
			"marketPrice": 19.23,
			"onCardTime2": "2013-05上牌",
			"oncardTime": "5年",
			"seriesName": "",
			"serviceCnt": "0,1,2,3,4,5",
			"showMeters": "2.0万公里",
			"showName": "奥迪A32018款 30周年纪念版 Sportback 35TFSI 进取版",
			"storeId": 1,
			"storeIntroduce": "应有尽有,物超所值",
			"ucid": "1"
		}
	}
}

我们就把这个json数据放入本地TomCat服务器下进行解析。

首先加入网络权限:

 

来看布局mainActivity.xml文件:




    


    

我们将这个json数据的carArchive对象中的数据用ListView进行展示,将usedCar对象中的数据用GridView数据进行展示。

注入OKHTTP及GSON依赖:

    implementation 'com.squareup.okhttp3:okhttp:3.2.0'
    implementation 'com.google.code.gson:gson:2.2.4'

来看MainActivity代码:

package com.example.administrator.newjsondata;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.GridView;
import android.widget.ListView;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private ListView lv_List;
    private List key2List;
    private List userList;
    private String path = "http://172.16.52.5:8080/zy3/Data2.json";  //TomCat服务器链接
    private GridView gv_List;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
    }

    private void initData() {

        new OkHttpClient().newCall(new Request.Builder().url(path).build()).enqueue(new Callback() {

            private List keyList;

            @Override
            public void onFailure(Call call, IOException e) {


            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                //获取json数据
                String string = response.body().string();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(string);
                    //最外层是对象,创建对象
                    JSONObject data = jsonObject.getJSONObject("data");
                    //data对象中还是对象(carArchive),再次创建对象
                    JSONObject carArchive = data.getJSONObject("carArchive");
                    //data对象中还是对象(usedCar),再次创建对象
                    JSONObject usedCar = data.getJSONObject("usedCar");
                    //通过key获取迭代器
                    Iterator iterator = carArchive.keys();
                    keyList = new ArrayList<>();
                    final List carArchiveList = new ArrayList<>();
                    //循环遍历迭代器
                    while (iterator.hasNext()) {
                        String next = iterator.next();
                        keyList.add(next);
                    }
                    //利用carArchiveList集合添加(通过carArchive对象获取中文key)
                    carArchiveList.add(carArchive.getString("2013-05上牌"));
                    carArchiveList.add(carArchive.getString("变速箱"));
                    carArchiveList.add(carArchive.getString("排放量"));
                    carArchiveList.add(carArchive.getString("排放标准"));
                    carArchiveList.add(carArchive.getString("来源"));
                    carArchiveList.add(carArchive.getString("看车地点"));
                    carArchiveList.add(carArchive.getString("表显里程"));
                    carArchiveList.add(carArchive.getString("车牌所在地"));
                    carArchiveList.add(carArchive.getString("过户次数"));
                    //更新UI 切换到主线程(可切换可不切换,毕竟就是在主线程)
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            gv_List.setAdapter(new MyAdapter(keyList, carArchiveList, MainActivity.this));
                        }
                    });


                    //同上
                    key2List = new ArrayList<>();
                    userList = new ArrayList<>();
                    Iterator keys1 = usedCar.keys();
                    while (keys1.hasNext()) {
                        keys1.hasNext();
                        key2List.add(keys1.next());
                    }
                    userList.add(usedCar.getString("brandName"));
                    userList.add(usedCar.getString("briefIntro"));
                    userList.add(usedCar.getString("carLocation"));
                    userList.add(usedCar.getString("constName"));
                    userList.add(usedCar.getString("deleteFlag"));
                    userList.add(usedCar.getString("discharge"));
                    userList.add(usedCar.getString("emission"));
                    userList.add(usedCar.getString("gearBox"));
                    userList.add(usedCar.getString("hotFiag"));
                    userList.add(usedCar.getString("isLaunch"));
                    userList.add(usedCar.getString("launchTime"));
                    userList.add(usedCar.getString("logoUrl"));
                    userList.add(usedCar.getString("marketPrice"));
                    userList.add(usedCar.getString("onCardTime2"));
                    userList.add(usedCar.getString("oncardTime"));
                    userList.add(usedCar.getString("seriesName"));
                    userList.add(usedCar.getString("serviceCnt"));
                    userList.add(usedCar.getString("showMeters"));
                    userList.add(usedCar.getString("showName"));
                    userList.add(usedCar.getString("storeId"));
                    userList.add(usedCar.getString("storeIntroduce"));
                    userList.add(usedCar.getString("ucid"));

                    lv_List.setAdapter(new MyAdapter(key2List, userList, MainActivity.this));

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

    }

    private void initView() {
        lv_List = (ListView) findViewById(R.id.lv_List);
        gv_List = (GridView) findViewById(R.id.gv_List);
    }
}

来看GridView(ListView)适配器

package com.example.administrator.newjsondata;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;

public class MyAdapter extends BaseAdapter {

    private List keyList;
    private List carArchiveList;
    private Context mContext;

    public MyAdapter(List keyList, List carArchiveList, Context mContext) {
        this.keyList = keyList;
        this.carArchiveList = carArchiveList;
        this.mContext = mContext;
    }

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

    @Override
    public Object getItem(int i) {
        return null;
    }

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

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder holder = null;
        if (view == null) {
            holder = new ViewHolder();
            view = LayoutInflater.from(mContext).inflate(R.layout.item_lv, null);
            holder.tv_name = view.findViewById(R.id.tv_name);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        holder.tv_name.setText(keyList.get(i) + ":" + "\r\n" + carArchiveList.get(i));
        return view;
    }

    class ViewHolder {
        TextView tv_name;
    }
}

适配器布局:




    

你可能感兴趣的:(android开发)