美文网首页
Android笔记之网络编程—初识解析JSON数据

Android笔记之网络编程—初识解析JSON数据

作者: RMaple_Qiu | 来源:发表于2016-08-24 17:36 被阅读139次

    我所学到的任何有价值的知识都是由自学中得来的。—— 达尔文

    小弟初学安卓,该文算是小弟的学习过程,课后笔记与一些自己的思考,希望在自己的自学路上留下印记,也许有一些自己想的不对的地方,希望各位前辈斧正。

    在网络中,数据的传输格式并不是随心所欲的,当我们想向服务器端传输数据或是从服务器端获取数据,这些数据都必须是格式化后的数据。这些数据有一定的结构规格和语义,任何一个接收数据方都必须对其进行解析才能获得他们想要得到的数据。

    网络传输的数据有两种常见的格式:XML(可扩展标记语言)和JSON(JavaScript Object Notation,是一种轻量级的数据交换格式)

    如何解析JSON

    首先我们先找一个测试用的.json文件来试试解析本地JSON文件,将其放在raw文件夹,我直接在自己电脑里搜索到了一个tsconfig.json文件(来自VS2015)来测试用:

    {
      "title": "test",
      "compilerOptions": {
        "noImplicitAny": false,
        "noEmitOnError": true
      },
      "exclude": [
        "node_modules",
        "wwwroot"
      ]
    }
    

    JSON的结构中,一对大括号代表的就是一个JSONObject,而中括号"["、"]"代表的就是一个JSONArray,而"title"这种则是属性。

    解析操作如下,将本地JSON文件读入输入流并转为字符串,作为创建JSONObject 实例的参数获得JSON对象:

    private String getStringByInputStream(InputStream in) {
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
    
    InputStream inputStream = getResources().openRawResource(R.raw.tsconfig);
    String jsonString = getStringByInputStream(inputStream);
    try {
        JSONObject jsonObject = new JSONObject(jsonString);
        JSONObject test = jsonObject.getJSONObject("compilerOptions");
        JSONArray jsonArray = jsonObject.getJSONArray("exclude");
        boolean noImplicitAny = test.getBoolean("noImplicitAny");
        Log.i("JSON", noImplicitAny + "   " + jsonArray.get(0));
    } catch (JSONException e) {
        e.printStackTrace();
    }
    break;
    

    若要解析网络返回的JSON数据,就首先连接网络请求“GET”方法,当HttpURLConnection对象执行connect()方法之后,就可以使用HttpURLConnection对象的getInputStream()方法将数据转换为输入流,并将其转换为字符串。

                BufferedReader reader;
                String result = null;
                StringBuffer sbf = new StringBuffer();
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(httpUrl);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.connect();
                    InputStream is = connection.getInputStream();
                    reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    String strRead;
                    while ((strRead = reader.readLine()) != null) {
                        sbf.append(strRead);
                        sbf.append("\r\n");
                    }
                    reader.close();
                    result = sbf.toString();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
    

    开源库GSON的简单使用(待未来补全)


    首先使用AS的GSON Format插件将JSON转换为JAVA实体类(这个实体类也可以自己写,插件只是替你生成),这个实体类中JSON对象会创建一个类,其中的属性为其变量,而JSON数组声明为集合。然后再为各个变量和集合生成get方法以便未来获得实体类对象后通过对象获取我们想要的数据。tsconfig.json文件生成的实体类就为:

    JsonData实体类
    import com.google.gson.annotations.SerializedName;
    
    import java.util.List;
    
    
    public class JsonData {
    
    
        /**
         * title : test
         * compilerOptions : {"noImplicitAny":false,"noEmitOnError":true}
         * exclude : ["node_modules","wwwroot"]
         */
    
        @SerializedName("title")
        private String mTitle;
        /**
         * noImplicitAny : false
         * noEmitOnError : true
         */
    
        @SerializedName("compilerOptions")
        private CompilerOptionsBean mCompilerOptions;
        @SerializedName("exclude")
        private List<String> mExclude;
    
        public String getTitle() {
            return mTitle;
        }
    
        public void setTitle(String title) {
            mTitle = title;
        }
    
        public CompilerOptionsBean getCompilerOptions() {
            return mCompilerOptions;
        }
    
        public void setCompilerOptions(CompilerOptionsBean compilerOptions) {
            mCompilerOptions = compilerOptions;
        }
    
        public List<String> getExclude() {
            return mExclude;
        }
    
        public void setExclude(List<String> exclude) {
            mExclude = exclude;
        }
    
        public static class CompilerOptionsBean {
            @SerializedName("noImplicitAny")
            private boolean mNoImplicitAny;
            @SerializedName("noEmitOnError")
            private boolean mNoEmitOnError;
    
            public boolean isNoImplicitAny() {
                return mNoImplicitAny;
            }
    
            public void setNoImplicitAny(boolean noImplicitAny) {
                mNoImplicitAny = noImplicitAny;
            }
    
            public boolean isNoEmitOnError() {
                return mNoEmitOnError;
            }
    
            public void setNoEmitOnError(boolean noEmitOnError) {
                mNoEmitOnError = noEmitOnError;
            }
        }
    }
    

    其中@SerializedName序列化变量名可以让我们的变量、类名、集合名与JSON中的对属性、对象、数组名相同,方便我们将JSON数据转换为实体类的对象。

    InputStream inputStream_2 = getResources().openRawResource(R.raw.tsconfig);
    String jsonString_2 = getStringByInputStream(inputStream_2);
    Gson gson = new Gson();
    JsonData jsonData = gson.fromJson(jsonString_2, JsonData.class);
    

    像现在我们获得了jsonData的对象了,比如我们要获得title的属性值和说compilerOptions对象的noEmitOnError属性的值,我们通过JSON文件可以看出这个属性的类型是boolean类型的,要获得这些值只要使用我们实体类写的相应的get方法就是了。我们用Log打印试试:

    Log.i("gson", jsonData.getTitle() + "  " + jsonData.getCompilerOptions().isNoEmitOnError());
    
    获取成功

    相关文章

      网友评论

          本文标题:Android笔记之网络编程—初识解析JSON数据

          本文链接:https://www.haomeiwen.com/subject/davnsttx.html