android生成json

package com.example.zzzz;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.Button;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
    }

    public void init() {
        JSONObject jsonObjArr1 = new JSONObject();
        JSONObject jsonObjArr2 = new JSONObject();
        JSONObject jsonObjArr3 = new JSONObject();
        JSONObject jsonObjArr4 = new JSONObject();
        
        // 创建json格式的数据
        JSONObject jsonObj = new JSONObject();

        // json格式的数组
        JSONArray jsonArr = new JSONArray();

        // json格式的数组
        JSONArray jsonArr2 = new JSONArray();

        try {

            jsonObjArr1.put("1001", "幼儿园");
            jsonObjArr1.put("1002", "小学");

            jsonObjArr2.put("2001", "初中");
            jsonObjArr2.put("2002", "高中");

            jsonObjArr3.put("3001", "职校");
            jsonObjArr3.put("3002", "中专");

            jsonObjArr4.put("4001", "学院");
            jsonObjArr4.put("4002", "大学");

            // 将json格式的数据放到json格式的数组里
            jsonArr.put(jsonObjArr1);
            jsonArr.put(jsonObjArr2);
            
            // 再将这个json格式的的数组放到最终的json对象中。
            jsonObj.put("初级", jsonArr);

            // 将json格式的数据放到json格式的数组里
            jsonArr2.put(jsonObjArr3);
            jsonArr2.put(jsonObjArr4);
            
            // 再将这个json格式的的数组放到最终的json对象中。
            jsonObj.put("高级", jsonArr2);

            Log.i("json:", jsonObj.toString());

        } catch (JSONException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

结果:

{"初级":[{"1001":"幼儿园","1002":"小学"},{"2002":"高中","2001":"初中"}],"高级":[{"3002":"中专","3001":"职校"},{"4002":"大学","4001":"学院"}]}

原文地址:https://www.cnblogs.com/liqw/p/3468820.html