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

2018-03-08  本文已影响0人  WangXiaoNao123

前言

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

每篇格言:

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

一、 什么是JSON:


二、JSON的特点:


三、JSON的数据格式:

1、JSON对象:

2、 JSON数组 :


四、JSON在不同环境中的解析


五、Android原生技术解析JSON

解析JSON对象

服务端(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数组

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


            }
        });
    }
}

上一篇下一篇

猜你喜欢

热点阅读