Android学习之JSON解析 (一) 原生技术解析JSON

前言

本人学生一枚,若文章中出现错误,请大佬指出。

每篇格言:

不管何时何地做你想做的事永远都不嫌晚,如果你发现生活不如意,我希望你有勇气重来

一、 什么是JSON:

  • 借用百科的介绍:
    JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式。
    它基于 ECMAScript (w3c制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。
    简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。

  • 自己的理解:本人感觉JSON相当于Java中的Map集合,通过Key-Value(键值对)的形式来保存数据。


二、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 = "{\n" +
                "\t\"id\":2, \"name\":\"WangXiaoNao\", \n" +
                "\t\"age\":20, \n" +
                "}\n";

        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 = "[\n" +
                "    {\n" +
                "        \"id\": 1,\n" +
                "        \"name\": \"路人甲\",\n" +
                "        \"age\": 20\n" +
                "    },\n" +
                "    {\n" +
                "        \"id\": 2,\n" +
                "        \"name\": \"路人乙\",\n" +
                "        \"age\": 10\n" +
                "    }\n" +
                "]";


        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();
                }


            }
        });
    }
}

你可能感兴趣的:(Android学习之JSON解析 (一) 原生技术解析JSON)