1、单个json数据的封装方法:

 /**
     * 封装单独的Json数据
     * @return
     */
    public String setJson() throws JSONException {

        JSONObject jsonObject=new JSONObject();
        JSONObject jsonstring=new JSONObject();

        jsonObject.put("name","张三");
        jsonObject.put("sex","男");
        jsonObject.put("age",23);

        //给json数据加上key
        jsonstring.put("Person",jsonObject);
        return jsonstring.toString();


    }

解析单个json数据的方法:

 /**
     * 解析单个json数据
     */
    public void analysisJSON(String json) throws JSONException {
        JSONObject jsonObject=new JSONObject(json);
        //通过key获取json数据
        JSONObject jsonobj=jsonObject.getJSONObject("Person");
        String name=jsonobj.getString("name");
        String sex=jsonobj.getString("sex");
        int age=jsonobj.getInt("age");

        System.out.println("姓名:"+name+",性别:"+sex+",年龄:"+age);

    }

2、封装JSON数组数据方法:

  /**
     * 发送json数组
     * 把数据封装成json数组
     * @return
     * @throws JSONException
     */
    public  String sendJSONArray() throws JSONException {

        //封装json数据数据
        JSONArray jsonArray=new JSONArray();
        JSONObject jsontostring=new JSONObject();

        JSONObject jsonObject1=new JSONObject();
        //张三
        jsonObject1.put("name","张三");
        jsonObject1.put("sex","男");
        jsonObject1.put("age",20);
        jsonArray.put(jsonObject1);
        JSONObject jsonObject2=new JSONObject();
        //李四
        jsonObject2.put("name","李四");
        jsonObject2.put("sex","男");
        jsonObject2.put("age",20);
        jsonArray.put(jsonObject2);
        JSONObject jsonObject3=new JSONObject();
        //王五
        jsonObject3.put("name","王五");
        jsonObject3.put("sex","男");
        jsonObject3.put("age",20);

        jsonArray.put(jsonObject3);//添加进入到数组中
        //将数组放到字符中Key-values形式存储
        jsontostring.put("Person",jsonArray);
        Log.d("debug1",jsontostring.toString());

        return jsontostring.toString();


    }

 解析JSON数组数据的方法:

  /**
     * 解析JSON格式数组
     */
    public void analysisJSONArray(String jsonstring){



        System.out.println("姓名:"+jsonstring);
        try {
            //解析成JSON对象
            JSONObject jsonObject= new JSONObject(jsonstring);
            //解析成JSON数组对象
            JSONArray jsonArray=jsonObject.getJSONArray("Person");//key
            //获取值
            for (int i=0;i<jsonArray.length();i++){

                //获取单个对象值Person
                JSONObject jsonobj=jsonArray.getJSONObject(i);


                String name=jsonobj.getString("name");
                String sex=jsonobj.getString("sex");
                int age=jsonobj.getInt("age");

                System.out.println(i+" ,姓名:"+name+",性别:"+sex+",年龄:"+age);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

 

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐