Basic JSONObject content (3): jsonobject content

Source: Internet
Author: User

Basic JSONObject content (3): jsonobject content

Reference: http://swiftlet.net/archives/category/json Thank you very much !!!~~

 

The third article mainly describes two points: 1. How to obtain the value of the corresponding key in JSONObject. 2. How to convert JSONObject to a javaBean object.

 

1) Get the attribute value in JSONObject

First, we write a javaBean class.

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

Then, generate an object according to the normal method, convert it to JSONObject, and then read the comment ~

Public static void main (String [] args) {Emp emp = new Emp (); emp. setName ("Rime"); emp. setAge (23); emp. setMarried (false); // convert to JSONObject json = JSONObject. fromObject (emp); System. out. println (json. toString (); // obtain the attribute value using the key, similar to String name = json in map. getString ("name"); Integer age = json. getInt ("age"); boolean married = json. getBoolean ("married"); System. out. println (name + "," + age + "," + married );}

Output result:

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

 

You may have doubts here. (1) What if the key does not exist in JSONObject? (2) The type of the value corresponding to this key is incorrect. What should I do? (3) What if value is a complex data type?

If you have any questions, we will solve them one by one.

 

(1) We intentionally wrote the "name" error as "nane". The system reports an error:

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

To prevent this exception, we can use the optXXX method instead of the getXXX method.

That is:

String name = json. optString ("nane"); // when the key does not exist in jsonObject, you can use optXXX to obtain the null value or default value, instead of reporting an exception.

Set the default value:

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

If the nane attribute does not exist, the notExits string is returned.

 

(2) Let's modify the program.

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

When you run the program, an error is reported:

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. This type of error occurs.

 

Note that {"age": 23, "married": false, "name": "false"}, where false without the "" number is of the boolean type, the string type is enclosed in quotation marks.

In addition, most types can be converted to string types, but in turn it will not work.

 

(3) complex data types

Write a bean with a complex point

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;

Then, generate an object and assign a value to the attribute

Public static void main (String [] args) {Student s = new Student (); List <String> sList = new Student List <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 (); // convert jsonObject to 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 ());}

Running result:

{"Age": 23, "birth": {"date": 7, "day": 2, "hours": 17, "minutes": 24, "month ": 6, "seconds": 33, "time": 1436261073641, "timezoneOffset":-480, "year": 115}, "courses": ["", "B"], "emp": {"age": 10, "married": false, "name": "me"}, "photo": {"d ": "d", "c": "c"}, "sname": "EZ "}
17:24:33 net. sf. json. JSONObject toBean
Information: Property 'day' of class java. util. Date has no write method. SKIPPED.
17:24:33 net. sf. json. JSONObject toBean
Information: 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

 

Although the data was successfully converted back, there was a warning, which made it difficult to feel at ease.

After careful observation, we can find that the above warnings are related to java. util. Date. What should we do with the Date type?

Also, pay attention to "birth": {"date": 8, "day": 3, "hours": 11, "minutes": 11, "month": 6, "seconds": 31, "time": 1436325091564, "timezoneOffset":-480, "year": 115 },

You will find that the data in this format is very difficult to understand, and we generally only need to use the format yyyy-MM-dd.

 

Ii) Date type

We can use the converter to convert the Date type.

First write a converter:

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

Then perform the test:

    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());    }

Final output result

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.