1、首先需要安装org.json.jar
2、类JSONObject用于创建一个json对象。其中的JSONObject.put(KEY, VALUE)用于向其中添加条目
3、JSONObject.getString(KEY)则用于从json对象中获取KEY对应的VALUE,且VALUE的类型为String
4、有时候,VALUE又是一个子json对象,此时我们可以用JSONObject.get(KEY)方法,从中KEY对应的子json对象,并将其类型转换为JSONObject
5、重复以上操作即可递归获取所要获取的内嵌VALUE字段
代码示例:
import org.json.JSONObject; public class JsonTest { public static void main(String[] args) { JSONObject json = new JSONObject(); json.put("name", "monster"); JSONObject education = new JSONObject(); education.put("highschool", "XSHS"); education.put("university", "HUST"); json.put("education", education); JSONObject hobby = new JSONObject(); json.put("hobby", hobby); System.out.println(json); String name = json.getString("name"); JSONObject object = (JSONObject)json.get("education"); String university = object.getString("university"); System.out.println("\"" + name + "\" finished university at \"" + university + "\""); } }
输出:
{"education":{"university":"HUST","highschool":"XSHS"},"name":"monster","hobby":{}} "monster" finished university at "HUST"
时间: 2024-10-26 16:57:20