Android开发json数据解析

         在Android开发过程中,或更新数据,或为减轻手机负担将大部分复杂运算交由服务器来进行,都需要与服务器之间进行数据交互,数据交互中,使用的较为频繁的格式变为json数据,书写便捷,操作方便,本文就对于客户端对于获取的json数据的解析进行一定的介绍。了解不是很深刻,只敢说简单应用,请测能用。

json数据书写比较简单,如下:

{
    "age": "24",
    "gender": "男",
    "hobby": "跑步,看书等",
    "name": "hill"
}

注意保存json文件时,格式要进行确定一直,特别是对于里面还有中文的时候。不然可能会出现乱码情况。Android开发json数据解析_第1张图片

而后就可以放置在服务器进行发布了。

界面布局比较随意,只是为了演示:

Android开发json数据解析_第2张图片

 界面代码为一个下载button,一个LinearLayout用于添加textview显示信息;

 下载并解析json文件如下:

public void loadjson(View view) {
        new Thread(){
            @Override
            public void run() {
                try {
                    URL Url=new URL("http://192.168.43.55:8080/jsonx.json");
                    HttpURLConnection conn=(HttpURLConnection)Url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setReadTimeout(5000);
                    int code = conn.getResponseCode();
                    if (code==200){
                        InputStream inputStream = conn.getInputStream();
                        String s = ToString(inputStream);
                        jiexi(s);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    private void jiexi(String s) throws JSONException {//解析显示数据
        JSONObject object=new JSONObject(s);
        System.out.println(s);
        String name = object.getString("name");
        String gender = object.getString("gender");
        String age = object.getString("age");
        String hobby = object.getString("hobby");
        final String[] strings = {name, gender, age, hobby};
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                for (String s :
                        strings) {
                    TextView textView=new TextView(getApplicationContext());
                    textView.setTextColor(Color.BLACK);
                    textView.setText(s);
                    ll_show.addView(textView);
                }
            }
        });

    }

    private String ToString(InputStream in) throws IOException {//将下载下来的流转换为string
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int len=-1;
        while ((len=in.read(bytes))!=-1){
            baos.write(bytes,0,len);
        }
        in.close();
        String s=new String(baos.toByteArray());
        return s;
    }

结果如下:

Android开发json数据解析_第3张图片

Android开发json数据解析_第4张图片 

 案例中用到了,利用java代码为线性布局添加控件:

TextView textView=new TextView(getApplicationContext());
                    textView.setTextColor(Color.BLACK);
                    textView.setText(s);
                    ll_show.addView(textView);

还是比较简单的,无需赘述。 

 

你可能感兴趣的:(Androidstudio)