《第一行代码》第二版 学习总结24 JSON数据解析

      最近利用下班时间,找了看什么书比较适合初学android的朋友,很多人推荐了这本书,于是就买了一本,感觉看书,思考,动手,再思考和总结这样过程还是很有必要的,于是就打算把自己学习的东西简单的总结一下;方便自己以后查找,也有利于学习的巩固。在这里首先要感谢一下书籍的作者——郭霖前辈。

      之前几篇介绍了关于如何访问网络数据,HttpURLConnection基本使用OkHttp基本使用;因为网络传输数据(文本数据)常用的用两种(XML和JSON)后者更轻量,但是语义没有前者好;但是毫无疑问,对于两种数据的处理,是我们网络访问数据避免不了的问题,今天我们就来看看Android对JSON的解析实现。如果你对JSON了解较少,你可以查看我的另一篇博客,里面有关于JSON的基本介绍

1,准备工作

这篇文章和XML数据解析是“兄弟篇”,准备工作参见XML数据解析;我这里给出原始的JSON数据如下(test.json):

[
{
"name":"why",
"age":"26",
"sex":"male"
},
{
"name":"jr",
"age":"24",
"sex":"female"
}

]

2,示例代码

MainActivity.java代码:

package com.hfut.operationjson;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

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

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

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

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    EditText jsonName;
    TextView jsonContent;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    jsonContent.setText((String) msg.obj);
                    break;

            }
        }
    };

    public final String localURL = "http://192.168.31.2:8088/";
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        jsonName = findViewById(R.id.json_name);
        jsonContent = findViewById(R.id.json_content);
    }

    public void jSONObjectParse(View view) {
        getData(view.getId());
    }

    public void gSONParse(View view) {
        getData(view.getId());
    }

    //JSONObject对象解析
    private String parseJSONwithJSONObject(String jsonData) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            JSONArray array = new JSONArray(jsonData);
            Log.i(TAG, "parseJSONwithJSONObject: "+array.length());
            //遍历json串,获取每一个json对象,在取键值对数据
            for (int i = 0; i < array.length(); i++) {
                JSONObject jsonObject = array.getJSONObject(i);
                String name = jsonObject.getString("name");
                String age = jsonObject.getString("age");
                String sex = jsonObject.getString("sex");
                stringBuilder.append("  name:"+name+";  age:"+age+";  sex:"+sex+"\n");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    //GSON解析
    private String parseJSONwithGSON(String jsonData) {
        Gson gson=new Gson();
        StringBuilder stringBuilder = new StringBuilder();
        //通过json字符串获取对象数组
        List<Student> list=gson.fromJson(jsonData,new TypeToken<List<Student>>(){}.getType());
            for (int i = 0; i < list.size(); i++) {
               Student student=list.get(i);
                String name = student.getName();
                String age =student.getAge();
                String sex = student.getSex();
                stringBuilder.append("  name:"+name+";  age:"+age+";  sex:"+sex+"\n");
            }
        return stringBuilder.toString();
    }


    private void getData(final int methodID){
        final StringBuilder stringBuilder = new StringBuilder();
        new Thread(new Runnable() {
            @Override
            public void run() {
                String tempUrl = localURL + jsonName.getText().toString();
                OkHttpClient okHttpClient = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(tempUrl)
                        .build();
                try {
                    Response response = okHttpClient.newCall(request).execute();
                    String result = response.body().string();
                    Message message = new Message();
                    String parsedData="";
                    //点击不同按钮,执行不同的解析方法
                    switch (methodID){
                        case R.id.JSONObjectWay:
                            parsedData=parseJSONwithJSONObject(result);
                            stringBuilder.append("解析方式为:JSONObjectWay\n");
                            break;
                        case R.id.GSONWay:
                            parsedData=parseJSONwithGSON(result);
                            stringBuilder.append("解析方式为:GSONWay\n");
                            break;
                    }
                    stringBuilder.append("源数据为:\n");
                    stringBuilder.append(result+"\n");
                    stringBuilder.append("解析数据结果:\n");
                    stringBuilder.append(parsedData);
                    message.what = 1;
                    message.obj = stringBuilder.toString();
                    handler.sendMessage(message);
                    Log.i(TAG, "run: " + result);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

Student.java代码:

package com.hfut.operationjson;

/**
 * author:why
 * created on: 2018/4/12 15:19
 * description:
 */
public class Student {
    private String name;
    private String age;
    private String sex;

    public String getName() {
        return name;
    }

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

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

activity_main.xml代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.hfut.operationjson.MainActivity">

    <EditText
        android:layout_marginTop="20dp"
        android:id="@+id/json_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入JSON文件名称"
        android:textSize="20dp" />

    <Button
        android:id="@+id/JSONObjectWay"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:textAllCaps="false"
        android:onClick="jSONObjectParse"
        android:text="JSONObject解析JSON"
        android:textSize="20dp" />

    <Button
        android:id="@+id/GSONWay"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:onClick="gSONParse"
        android:text="GSON解析JSON"
        android:textSize="20dp" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="10dp">

        <TextView
            android:textSize="20dp"
            android:textColor="@color/colorPrimary"
            android:id="@+id/json_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="显示服务器JSON文件数据" />
    </ScrollView>

</LinearLayout>

主配置文件AndroidManifest.xml代码:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hfut.operationjson">
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

3,运行结果

第一步:运行程序

第二步:点击“JSONObject解析JSON”

第三步:点击“GSON解析JSON”

其实有很多不错的开源库用于处理JSON数据,但是我觉得基本的使用这两种方式足够了。这里我写的非常的简单,其实你在我的另一篇博客里面会发现,其实GSON功能还是非常多的。

注:欢迎扫码关注

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值