解析JSON字符串:
我们可以通过JSONObject与JSONArray的getInt,getString,getDouble,getJSONArray,getJSONObject等函数来解析json.
package com.yunos.tv.video.resource.controller.web;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class Test {
public static void main(String[] args) {
String jsonString = "{\"UserName\":\"ZHULI\",\"age\":\"30\",\"workIn\":\"ALI\",\"Array\":[\"ZHULI\",\"30\",\"ALI\"]}";
//将Json字符串转为java对象
JSONObject obj = JSONObject.fromObject(jsonString);
//获取Object中的UserName
if (obj.has("UserName")) {
System.out.println("UserName:" + obj.getString("UserName"));
}
//获取ArrayObject
if (obj.has("Array")) {
JSONArray transitListArray = obj.getJSONArray("Array");
for (int i = 0; i < transitListArray.size(); i++) {
System.out.print("Array:" + transitListArray.getString(i) + " ");
}
}
}
}
返回:
UserName:ZHULI
Array:ZHULI Array:30 Array:ALI