JSON学习-org.json

package json;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Start {

/**
* @param args
* @throws JSONException
* 一个{}代表一个非基本类型对象,一个:前面的代表的是域名,:后面的代表数值([]则代表域名是数组类型)
*/
public static void main(String[] args) throws JSONException {
// TODO Auto-generated method stub

Integer[] a ={1,2,3,4,5,6};
String b="wangyuelin";
List l = new ArrayList();
l.add("1");
l.add("2");
System.out.println(new JSONArray(a));            //[1,2,3,4,5,6]

// System.out.println(new JSONArray(b));            //ERROR: AJSONArray text must start with '[' at character 1 必须是数组


System.out.println(new JSONArray(b.toCharArray())); //["w","a","n","g","y","u","e","l","i","n"]
                System.out.println(new JSONArray(l));                    //["1","2"]

                System.out.println("******************");

System.out.println(new JSONObject(a));               //{}
// System.out.println(new JSONObject(b));           //ERROR: A JSONObject text must begin with '{' at character 1

 

//String在JSONObject中比较特殊,他需要正确的JSON格式 才可以运作,比如

 

System.out.println(new JSONObject("{'name':'wangyuelin'}"));  //{"name":"wangyuelin"}
System.out.println(new JSONObject(new Student()));  //Student中必须含有get方法才可以得到正确的 jsonobject,否则为空{}    {"address":"suzhou","name":"wangyuelin","age":12}
System.out.println(new JSONObject((Object)b));     

//自动调用了getBytes()和isEmpty()无参方法:{"bytes":[119,97,110,103,121,117,101,108,105,110],"empty":false}

 

System.out.println(new JSONObject(l));              //ArrayList中isEmpty()的无参构造方法,故为{}

System.out.println("******************");           //以键值对的形式放入


JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "wangyuelin");
jsonObject.put("sex", "男");  
jsonObject.put("QQ", "413425430"); 

jsonObject.put("student",new JSONObject(new Student()));  // 加入新object,以键值对形式(String :

String)形式存入


System.out.println(jsonObject);                       //{"sex":"男","QQ":"413425430","name":"wangyuelin"}


System.out.println("******************");           //增加JSONArray


JSONArray ja = new JSONArray();
ja.put(0,"1");
ja.put(1,"2");
ja.put(2,"3");                                    
jsonObject.put("我来数数", ja);
System.out.println(jsonObject);
}

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值