SoFunction
Updated on 2025-03-01

Detailed explanation of Json generation and analysis and example code

Json generation and analysis

JSON is commonly used to interact with servers in data. In JSON, "{}" means JSONObject, "[]" means JSONArray

The following json data:

1 {"singers":[
2 {"id":"02","name":"tom","gender":"male","tel":["123456","789012"]},
3 {"id":"03","name":"jerry","gender":"male","tel":["899999","666666"]},
4 {"id":"04","name":"jim","gender":"male","tel":["7777","5555"]},{"id":"05","name":"lily","gender":"female","tel":["222222","111111"]}
5 ]}

Generate json data code:

public String buildJson() throws JSONException {

    JSONObject persons = new JSONObject();

    JSONArray personArr = new JSONArray();

    JSONObject person = new JSONObject();
    ("id", "02");
    ("name", "tom");
    ("gender", "male");

    JSONArray tel = new JSONArray();
    ("123456");
    ("789012");

    ("tel", tel);

    (person);

    JSONObject person2 = new JSONObject();
    ("id", "03");
    ("name", "jerry");
    ("gender", "male");

    JSONArray tel2 = new JSONArray();
    ("899999");
    ("666666");

    ("tel", tel2);

    (person2);


    JSONObject person3 = new JSONObject();
    ("id", "04");
    ("name", "jim");
    ("gender", "male");

    JSONArray tel3 = new JSONArray();
    ("7777");
    ("5555");

    ("tel", tel3);

    (person3);


    JSONObject person4 = new JSONObject();
    ("id", "05");
    ("name", "lily");
    ("gender", "female");

    JSONArray tel4 = new JSONArray();
    ("222222");
    ("111111");

    ("tel", tel4);

    (person4);


    ("singers", personArr);


    return ();
  }

Parse json data code:

private void parseJsonMulti(String strResult) {
    try {
      JSONArray jsonObjs = new JSONObject(strResult).getJSONArray("singers");
      String s = "";

      for (int i = 0; i < (); i++) {
        JSONObject jsonObj = ((JSONObject) (i));
        int id = ("id");
        String name = ("name");
        String gender = ("gender");
        s += "ID number" + id + ", Name:" + name + ",gender:" + gender + ",Telephone:";
        JSONArray tel = ("tel");
        for (int j = 0; j < (); j++) {

          s += (j)+"/";
        }

        s += "\n";

      }
      (s);
    } catch (JSONException e) {
      ();
    }
  }

Thank you for reading, I hope it can help you. Thank you for your support for this site!