你的位置:首页 > Java教程

[Java教程]JSONObject基本内容(三)


参考资料:http://swiftlet.net/archives/category/json    十分感谢!!!~~

 

第三篇的内容,主要讲述的有两点: 1 .如何获取JSONObject中对应key的value。   2.如何把JSONObject转换为javaBean对象。

 

一)获取JSONObject中属性值

首先我们写一个javaBean类

public class Emp {  private String name;  private Integer age;  private boolean married;    public boolean isMarried() {    return married;  }  public void setMarried(boolean married) {    this.married = married;  }  public String getName() {    return name;  }  public void setName(String name) {    this.name = name;  }  public Integer getAge() {    return age;  }  public void setAge(Integer age) {    this.age = age;  }}

然后按正常方法,生成对象,把它转换为JSONObject,接着看注释吧~

  public static void main(String[] args) {    Emp emp = new Emp();    emp.setName("Rime");    emp.setAge(23);    emp.setMarried(false);        //转换为JSONObject    JSONObject json = JSONObject.fromObject(emp);    System.out.println(json.toString());        //利用key获取属性值,和map相似    String name = json.getString("name");    Integer age = json.getInt("age");    boolean married = json.getBoolean("married");    System.out.println(name + "," + age + "," + married);      }

输出结果:

{"age":23,"married":false,"name":"Rime"}
Rime,23,false

 

看到这里你或许会有疑问,(1)假如JSONObject中并没有这个key存在,会怎么样?(2)这个key对应的value的类型错了,怎么办?(3)如果value是复杂数据类型,怎么办?

既然有疑问,那么我们一个一个解决。

 

(1)我们故意把"name"写错,写成"nane",结果系统报错:

Exception in thread "main" net.sf.json.JSONException: JSONObject["nane"] not found

为了防止这种异常,我们可以用optXXX方法,来代替getXXX方法。

即:

 String name = json.optString("nane");//当jsonObject中不存在该key时,可以用optXXX来获取空值或者默认值,而不是报异常

设置默认值:

String name = json.optString("nane","notExits");

设置默认之后,当nane属性不存在时,返回notExits字符串。

 

(2)我们把程序修改一下

    String name = json.getString("age");    boolean married = json.getBoolean("name");    Integer age = json.getInt("name");

运行程序,会报错:

Exception in thread "main" net.sf.json.JSONException: JSONObject["name"] is not a Boolean.

Exception in thread "main" net.sf.json.JSONException: JSONObject["name"] is not a number.这一类错误。

 

特别要注意的是{"age":23,"married":false,"name":"false"},其中没带""号的false是boolean类型,带引号的是字符串类型。

还有就是大多数类型可以转换为字符串类型,但是反过来就不行了。

 

(3)复杂数据类型

写一个复杂点的bean

public class Student implements Serializable{  private static final long serialVersionUID = 1L;  private String sname;  private Integer age;  private Date birth;  private List<String> courses;  private Map<String,String> photo;  private Emp emp;

然后,生成对象,给属性赋值

  public static void main(String[] args) {    Student s = new Student();    List<String> sList = new LinkedList<String>();    Map<String,String> photos = new HashMap<String,String>();    Emp emp = new Emp();    emp.setName("me");    emp.setAge(10);    emp.setMarried(false);        sList.add("a");    sList.add("b");        photos.put("c", "c");    photos.put("d", "d");        s.setSname("EZ");    s.setAge(23);    s.setBirth(new Date());    s.setCourses(sList);    s.setPhoto(photos);    s.setEmp(emp);        JSONObject jsonObject = JSONObject.fromObject(s);    System.out.println(jsonObject.toString());        //jsonObject转换为javaBean        Student student = (Student) JSONObject.toBean(jsonObject, Student.class);    System.out.println(student.getSname() + ";" + student.getAge() + ";" +student.getBirth() + ";" + student.getCourses().get(1) + ";" + student.getPhoto().get("c") + ";" + student.getEmp());  }

运行结果:

{"age":23,"birth":{"date":7,"day":2,"hours":17,"minutes":24,"month":6,"seconds":33,"time":1436261073641,"timezoneOffset":-480,"year":115},"courses":["a","b"],"emp":{"age":10,"married":false,"name":"me"},"photo":{"d":"d","c":"c"},"sname":"EZ"}
2015-7-7 17:24:33 net.sf.json.JSONObject toBean
信息: Property 'day' of class java.util.Date has no write method. SKIPPED.
2015-7-7 17:24:33 net.sf.json.JSONObject toBean
信息: Property 'timezoneOffset' of class java.util.Date has no write method. SKIPPED.
EZ;23;Tue Jul 07 17:24:33 CST 2015;b;c;com.vmaxtam.json.Emp@43b09468

 

虽然顺利把数据转换回去了,但是出现了警告信息,总让人无法安心下来。

如果仔细观察,可以发现,以上警告都是有关 java.util.Date 的警告,那么Date类型该如何处理呢?

并且,留意   "birth":{"date":8,"day":3,"hours":11,"minutes":11,"month":6,"seconds":31,"time":1436325091564,"timezoneOffset":-480,"year":115},

你会发现这个格式的数据十分难懂,而且我们一般只要用到yyyy-MM-dd这种格式。

 

二)Date类型

关于Date类型的转换,我们可以通过转换器来实现。

先写一个转换器:

public class JsonDateValueProcessor implements JsonValueProcessor {  private String datePattern = "yyyy-MM-dd";  public JsonDateValueProcessor() {    super();  }  public JsonDateValueProcessor(String format) {    super();    this.datePattern = format;  }  @Override  public Object processArrayValue(Object value, JsonConfig jsonConfig) {    return process(value);  }  @Override  public Object processObjectValue(String key, Object value,      JsonConfig jsonConfig) {    return process(value);  }  private Object process(Object value) {    try {      if (value instanceof Date) {        SimpleDateFormat sdf = new SimpleDateFormat(datePattern,            Locale.UK);        return sdf.format((Date) value);      }      return value == null ? "" : value.toString();    } catch (Exception e) {      return "";    }  }  public String getDatePattern() {    return datePattern;  }  public void setDatePattern(String pDatePattern) {    datePattern = pDatePattern;  }}

然后再进行测试:

  public static void main(String[] args) {    Student s = new Student();    s.setBirth(new Date());        JsonConfig config = new JsonConfig();    config.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());            JSONObject jsonObject = JSONObject.fromObject(s,config);    System.out.println(jsonObject.toString());  }

最后输出的结果

{"age":0,"birth":"2015-07-08","courses":[],"emp":null,"photo":null,"sname":""}