<span style="font-family:Microsoft YaHei;font-size:12px;">//JSON字符串里取值
String str1 = "{ 'name': 'cxh', 'sex': '1' }";
JSONObject obj = JSONObject.fromObject(str1);
String name = obj.getString("name"); //返回字符型
Object nameObj = obj.get("name"); //返回对象性
int age = ibj.getInt("sex"); //返回int型
//JSON数组里取值
String jsonArrStr = "[ { 'name': 'cxh', 'sex': '1','website':'http://www.bejson.com' },
{ 'name': '三少', 'sex': '1','website':'http://www.ij2ee.com' } ]";
JSONArray array = JSONArray.fromObject(jsonArrStr);
for(int i = 0 ; i <array.size() ; i++){
JSONObject jsonObj = array.getJSONObject( i );
System.out.println(jsonObj.getString("website"));
}
//将Bean对象转换为JSON对象
User user = new User();
user.setName("cxh");
user.setSex(1);
user.setWebsite("http://www.baidu.com");
JSONObject jo2 = JSONObject.fromObject(user);
System.out.println(jo2.toString); </span>
<span style="font-family:Microsoft YaHei;font-size:12px;">//则会输出 { 'name': 'cxh', 'sex': '1','website':'http://www.baidu.com'}
//JSON对象里put "String",JSON数组里put Object
public static void JSONArray_1(){
ArrayList<UserDto> arrayList = new ArrayList<UserDto>();
UserDto userDto = new UserDto();
userDto.userId = "00001";
userDto.userNm = "JOHN";
userDto.deptID = "10";
userDto.deptNm = "HR1";
arrayList.add(userDto);
JSONArray jsonArray = new JSONArray();
try {
for(UserDto dto:arrayList){
JSONObject jsonObject = new JSONObject();
jsonObject.put("userId", dto.userId);
jsonObject.put("userNm", dto.userNm);
jsonObject.put("deptId", dto.deptID);
jsonObject.put("deptNm", dto.deptNm); //放入JSON对象
jsonArray.put(jsonObject); //放入JSON数组
}
System.out.println("jsonArray =" + jsonArray);
//JSON数组里取出JSON对象,JSON对象里取出“String”
Object object2 ;
for(int i = 0 ; i < jsonArray.length(); i++){
JSONObject jsonObject = (JSONObject) jsonArray.get(i); //取出JSON对象
object2 = jsonObject.get("userId"); //取出名称对应的值
System.out.println("userId =" + object2);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
//创建包含数组型JSON数据
JSONObject jsonObj = newJSONObject();
JSONStringjsonStr= new JSONString("apple");
jsonObj.put("apple",jsonStr);
JSONArray arrayValue = new JSONArray();
arrayValue.set(0, new JSONString("array item 0 "));
arrayValue.set(1, new JSONString("array item 1 "))
arrayValue.set(2, new JSONString("array item 2 "));
jsonObj.put("array",arrayValue);
//则jsonObj的 JSON的数据格式
{name: "apple",
array: { "array item 0 ","array item 1 " ,"array item 2" }
}
</span>