* json中只要是{}就代表⼀个JSONObject,[]就代表⼀个JSONArray
* 获取JSONObject对象⽤JSONObject("key")⽅法
* 获取JSONArray对象⽤JSONArray("key")⽅法
*/
private static void strWritedToJSONObject() {
//以下是⼀个json对象中嵌套⼀个json⼦对象
String myJsonObj = "{\n" +
" \"name\":\"runoob\",\n" +
" \"alexa\":10000,\n" +
" \"sites\": {\n" +
" \"site1\":\"www.runoob\",\n" +
" \"site2\":\"m.runoob\",\n" +
" \"site3\":\"c.runoob\"\n" +
" }\n" +
"}";
JSONObject jsonobj = JSON.parseObject(myJsonObj); //将json字符串转换成jsonObject对象
/***获取JSONObject中每个key对应的value值时,可以根据实际场景中想得到什么类型就分别运⽤不到的⽅法***/
System.out.("name")); //取出name对应的value值,得到的是⼀个object
System.out.String("name")); //取出name对应的value值,得到的是⼀个String
System.out.IntValue("alexa")); //取出name对应的value值,得到的是⼀个int
System.out.("sites")); //取出sites对应的value值,得到的是⼀个object
System.out.String("sites"));
System.out.JSONObject("sites")); //取出sites对应的value值,得到⼀个JSONObject⼦对象
System.out.JSONObject("sites").getString("site2")); //取出嵌套的JSONObject⼦对象中site2对应的value值,必须⽤getJSONObject()先获取JSONObject /**
* 以下是⼀个json对象中包含数组,数组中⼜包含json⼦对象和⼦数组
*/
String myJsonObj2 = "{\n" +
" \"name\":\"⽹站\",\n" +
" \"num\":3,\n" +
" \"sites\": [\n" +
" { \"name\":\"Google\", \"info\":[ \"Android\", \"Google 搜索\", \"Google 翻译\" ] },\n" +
" { \"name\":\"Runoob\", \"info\":[ \"菜鸟教程\", \"菜鸟⼯具\", \"菜鸟\" ] },\n" +
" { \"name\":\"Taobao\", \"info\":[ \"淘宝\", \"⽹购\" ] }\n" +
" ]\n" +
"}";
JSONObject jsonobj2 = JSON.parseObject(myJsonObj2); //将json字符串转换成jsonObject对象
System.out.("sites"));
System.out.String("sites"));
System.out.JSONArray("sites")); //取出sites对应的value值,得到⼀个JSONOArray对象
//System.out.JSONObject("sites")); 不能⽤该⽅法,因为sites是⼀个JSONOArray对象
//取出json对象中sites对应数组中第⼀个json⼦对象的值
System.out.JSONArray("sites").getJSONObject(0)); //得到结果:{"name":"Google
","info":["Android","Google 搜索","Google 翻译"]}
System.out.JSONArray("sites").get(0));
System.out.JSONArray("sites").getString(0));
json转换对象//取出json对象中sites对应数组中第⼀个json⼦对象下⾯info对应的嵌套⼦数组值
System.out.JSONArray("sites").getJSONObject(0).getJSONArray("info")); //得到结果:["Android","Google 搜索","Google 翻译"]
//取出json对象中sites对应数组中第⼀个json⼦对象下⾯info对应的嵌套⼦数组中第⼆个值
System.out.JSONArray("sites").getJSONObject(0).getJSONArray("info").getString(1)); //得到结果:Google 搜索
//依次取出json对象中sites对应数组中的值
JSONArray array = JSONArray("sites");
getJsonArrayItem(array);
//依次取出json对象中sites对应数组中第⼆个json⼦对象下⾯info对应的嵌套⼦数组值
JSONArray arr = JSONArray("sites").getJSONObject(1).getJSONArray("info");
getJsonArrayItem(arr);
}
/**
* ⼿动添加对象到⼀个JSONObject
*/
private static void writeStrToJSONObject() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name","tom");
jsonObject.put("age",20);
JSONArray jsonArray = new JSONArray();
JSONObject jsonArrayObject1 = new JSONObject();
jsonArrayObject1.put("name","alibaba");
jsonArrayObject1.put("info","www.alibaba");
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论