Android学習のJSON解析(一)原生技術解析JSON

10556 ワード

前言
私の学生は1枚、もし文章の中で が現れたら、 に指摘してください.
各格言:
                  ,          ,         

一、JSONとは何ですか.
  • 借用百科事典の紹介:JSON(JavaScript Object Notation,JSオブジェクトタグ)は軽量レベルのデータ交換フォーマットである.ECMAScript(w 3 cが制定したjs仕様)のサブセットに基づいて、プログラミング言語とは完全に独立したテキストフォーマットを用いてデータを格納し、表す.簡潔で明確な階層はJSONを理想的なデータ交換言語にした.読み取りと作成が容易であり、同時に機械の解析と生成が容易であり、ネットワーク伝送効率を効果的に向上させる.
  • 自己の理解:JSONはJavaの中のMap集合に相当すると感じ、KeyValue(キー値ペア)の形でデータを保存する.

  • 二、JSONの特徴:
  • 利点:
      JSON     ,               。        ,            。
    
  • 欠点:
          ,     XML  。
    
  • 三、JSONのデータフォーマット:
    1、JSON対象:
  • 形式:
    { "firstName":"John" , "lastName":"Doe" }
    
  • keyキーデータ型:String(文字列)
  • Valueデータ型:String、null、JSONオブジェクト、JSON配列、数値
  • 2、JSON配列:
  • 形式:
      {
         "employees": [{
                 "firstName": "John",
                 "lastName": "Doe"
             },
             {
                 "firstName": "Anna",
                 "lastName": "Smith"
             },
             {
                 "firstName": "Peter",
                 "lastName": "Jones"
             }
         ]
     }
    
  • 四、JSONの異なる環境における解析
  • サービス側(Java):
       Java     JSON      
    
  • クライアント(Android):
       JSON        Java  
    
  • 五、Android原生技術解析JSON
  • 欠点:Android原生技術解析JSONは特に煩雑で、複雑なJSONデータに対してエラーが発生しやすい.

  • 解析JSONオブジェクト
  • 関連API:
  • JSONObject(String json);Json文字列をJsonオブジェクトに解析します.
  • XxxgetXxx(String name) ;nameに基づいてjsonオブジェクトに対応するvalueが得られる.

  • ケース:
  • サービス側(Java):
    public class JsonOneServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doGet(request, response);
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setCharacterEncoding("utf-8");
    
            String json = "{
    " + "\t\"id\":2, \"name\":\"WangXiaoNao\",
    " + "\t\"age\":20,
    " + "}
    "; response.getWriter().println(json); } }

    モバイル端末(Android):
    public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    
        private static final String TAG = "MainActivity";
        private Button mSend;
        private TextView mResponse;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            mSend = findViewById(R.id.send);
            mSend.setOnClickListener(this);
            
            mResponse = findViewById(R.id.response);
            
        }
    
        private void sendRequestWithHttpURLConnection() {
    
            //           
            new Thread(new Runnable() {
                @Override
                public void run() {
                    BufferedReader mReader = null;
                    HttpURLConnection mConnection = null;
                    try {
                        //   :              ,     url        ip  
                        URL url = new URL("http://xxx:8080/JsonOne");
                        mConnection = (HttpURLConnection) url.openConnection();
                        mConnection.setRequestMethod("GET");
                        mConnection.setConnectTimeout(8000);
                        mConnection.setReadTimeout(8000);
                        InputStream in = mConnection.getInputStream();
                        //            
                        mReader = new BufferedReader(new InputStreamReader(in));
                        StringBuffer response = new StringBuffer();
                        String line;
                        while ((line = mReader.readLine()) != null) {
                            response.append(line);
                        }
                        showResponse(response.toString());
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (mReader != null) {
                            try {
                                mReader.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (mConnection != null) {
                            mConnection.disconnect();
    
                        }
                    }
    
    
                }
            }).start();
    
    
        }
    
        private void showResponse(final String s) {
    
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mResponse.setText(s);
                    Log.d(TAG, "run: --->" + s);
    
    
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        int id = jsonObject.optInt("id");
                        String name = jsonObject.optString("name");
                        int age = jsonObject.optInt("age");
                        Log.d(TAG, "  JSON   :" + "id=" + id + "name=" + name + "age=" + age);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    
    
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.send:
                    sendRequestWithHttpURLConnection();
                    break;
    
            }
    
        }
    }
    
    

    六、JSON配列の解析
  • 関連API:
  • JSONArray(String json);json文字列をjson配列に解析する.
  • int length();json配列中の要素の個数を得る.
  • XxxgetXxx(int s) ;json配列に対応する要素データを下付き文字に基づいて得た.

  • ケース:
  • サービス側(Java)
    public class JsonTwoServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
            this.doGet(request,response);
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setCharacterEncoding("utf-8");
    
    
            String json = "[
    " + " {
    " + " \"id\": 1,
    " + " \"name\": \" \",
    " + " \"age\": 20
    " + " },
    " + " {
    " + " \"id\": 2,
    " + " \"name\": \" \",
    " + " \"age\": 10
    " + " }
    " + "]"; response.getWriter().println(json); } }

    モバイル端末(Android)
    public class JSONActivity extends AppCompatActivity implements View.OnClickListener {
    
        private Button mSendTwo;
        private TextView mResponse;
        private static final String TAG = "JSONActivity";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_json);
    
    
            mSendTwo = findViewById(R.id.sendTwo);
            mSendTwo.setOnClickListener(this);
            mResponse = findViewById(R.id.response);
    
        }
    
        @Override
        public void onClick(View view) {
            if (view.getId() == R.id.sendTwo) {
                sendRequestWithHttpURLConnectionTwo();
            }
    
        }
    
        private void sendRequestWithHttpURLConnectionTwo() {
    
            //           
            new Thread(new Runnable() {
                @Override
                public void run() {
                    BufferedReader mReader = null;
                    HttpURLConnection mConnection = null;
                    try {
                        URL url = new URL("http://xxx:8080/JsonTwo");
                        mConnection = (HttpURLConnection) url.openConnection();
                        mConnection.setRequestMethod("GET");
                        mConnection.setConnectTimeout(8000);
                        mConnection.setReadTimeout(8000);
                        InputStream in = mConnection.getInputStream();
                        //            
                        mReader = new BufferedReader(new InputStreamReader(in));
                        StringBuffer response = new StringBuffer();
                        String line;
                        while ((line = mReader.readLine()) != null) {
                            response.append(line);
                        }
                        showResponse(response.toString());
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (mReader != null) {
                            try {
                                mReader.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (mConnection != null) {
                            mConnection.disconnect();
    
                        }
                    }
    
    
                }
            }).start();
    
    
        }
    
        private void showResponse(final String s) {
    
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
    
                        JSONArray jsonArray = new JSONArray(s);
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            if (jsonObject != null) {
                                int id = jsonObject.optInt("id");
                                String name = jsonObject.getString("name");
                                int age = jsonObject.getInt("age");
                                Log.d(TAG, "  JSON   :" + "id=" + id + "name=" + name + "age=" + age);
    
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
    
    
                }
            });
        }
    }