JAVA/JSON

<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>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值