1. รู้เบื้องต้นเกี่ยวกับ JSON-Java
JSON (ตัวย่อสำหรับ JavaScript Object Notation) เป็นรูปแบบการแลกเปลี่ยนข้อมูลที่มีน้ำหนักเบาและมักใช้สำหรับการสื่อสารไคลเอนต์เซิร์ฟเวอร์ ทั้งอ่าน / เขียนได้ง่ายและไม่ขึ้นกับภาษา ค่า JSON อาจเป็นออบเจ็กต์ JSON อาร์เรย์ตัวเลขสตริงบูลีน (จริง / เท็จ) หรือnull อื่น
ในบทช่วยสอนนี้เราจะดูว่าเราสามารถสร้างจัดการและแยกวิเคราะห์ JSON โดยใช้ไลบรารีการประมวลผล JSON ที่มีอยู่ได้อย่างไรเช่นไลบรารี JSON-Java หรือที่เรียกว่าorg.json
2. ข้อกำหนดเบื้องต้น
ก่อนที่เราจะเริ่มต้นเราจะต้องเพิ่มการอ้างอิงต่อไปนี้ในpom.xmlของเรา:
org.json json 20180130
เวอร์ชันล่าสุดสามารถพบได้ในที่เก็บ Maven Central
โปรดทราบว่าแพ็คเกจนี้ได้รวมอยู่ใน Android SDK แล้วดังนั้นเราจึงไม่ควรรวมไว้ในขณะที่ใช้งานเดียวกัน
3. JSON ใน Java [package org.json]
ไลบรารี JSON-Java เป็นที่รู้จักกันในชื่อorg.json (เพื่อไม่ให้สับสนกับ org.json.simple ของ Google) มีคลาสที่ใช้ในการแยกวิเคราะห์และจัดการ JSON ใน Java
นอกจากนี้ไลบรารีนี้ยังสามารถแปลงระหว่าง JSON, XML, HTTP Headers, Cookies, Comma-Delimited List หรือ Text เป็นต้น
ในบทช่วยสอนนี้เราจะดู:
- JSONObject - คล้ายกับแผนที่ดั้งเดิมของ Javaเช่น object ซึ่งเก็บคู่คีย์ - ค่าที่ไม่ได้เรียงลำดับ
- JSONArray - ลำดับของค่าที่คล้ายกับการใช้งาน Vector ดั้งเดิมของ Java
- JSONTokener - เครื่องมือที่แบ่งข้อความออกเป็นชุดโทเค็นซึ่ง JSONObjectหรือ JSONArrayสามารถใช้เพื่อแยกวิเคราะห์สตริง JSON
- CDL - เครื่องมือที่มีวิธีการแปลงข้อความที่คั่นด้วยจุลภาคเป็น JSONArrayและในทางกลับกัน
- คุกกี้ - แปลงจาก JSON Stringเป็นคุกกี้และในทางกลับกัน
- HTTP - ใช้ในการแปลงจาก JSON Stringเป็น HTTP headers และในทางกลับกัน
- JSONException - นี่คือข้อยกเว้นมาตรฐานที่ไลบรารีนี้ส่งมา
4. JSONObject
JSONObjectเป็นคอลเลกชันเรียงลำดับของคีย์และค่าคู่คล้ายของ Java พื้นเมืองแผนที่การใช้งาน
- คีย์เป็นสตริงเฉพาะที่ไม่สามารถเป็นค่าว่างได้
- ค่าสามารถเป็นอะไรก็ได้จากวัตถุบูลีน , ตัวเลข , สตริง , JSONArrayหรือแม้แต่วัตถุJSONObject.NULL
- JSONObjectสามารถแสดงโดยStringอยู่ภายในวงเล็บปีกกากับคีย์และค่าที่คั่นด้วยเครื่องหมายและคู่คั่นด้วยเครื่องหมายจุลภาค
- มีตัวสร้างหลายตัวที่ใช้สร้างJSONObject
นอกจากนี้ยังรองรับวิธีการหลักดังต่อไปนี้:
- รับ (คีย์สตริง) - g ets วัตถุที่เกี่ยวข้องกับคีย์ที่ให้มาพ่นJSONExceptionหากไม่พบคีย์
- การเลือก (String กุญแจ) - กรัม ETS วัตถุที่เกี่ยวข้องกับคีย์จัดnullมิฉะนั้น
- ใส่ (คีย์สตริงค่าออบเจ็กต์) -แทรกหรือแทนที่คู่คีย์ - ค่าในJSONObjectปัจจุบัน
ใส่ ()วิธีการเป็นวิธีการที่มากเกินไปซึ่งรับสำคัญของประเภทสตริงและหลายประเภทสำหรับค่า
สำหรับรายการวิธีการทั้งหมดที่JSONObjectสนับสนุนโปรดไปที่เอกสารอย่างเป็นทางการ
ตอนนี้เรามาพูดถึงการดำเนินการหลักบางอย่างที่คลาสนี้รองรับ
4.1. การสร้าง JSON โดยตรงจากJSONObject
JSONObject exposes API ที่คล้ายกับของ Java แผนที่อินเตอร์เฟซ เราสามารถใช้เมธอดput ()และใส่คีย์และค่าเป็นอาร์กิวเมนต์:
JSONObject jo = new JSONObject(); jo.put("name", "jon doe"); jo.put("age", "22"); jo.put("city", "chicago");
ตอนนี้JSONObjectของเราจะมีลักษณะดังนี้:
{"city":"chicago","name":"jon doe","age":"22"}
มีลายเซ็นโอเวอร์โหลดที่แตกต่างกันเจ็ดแบบของเมธอดJSONObject.put () แม้ว่าคีย์จะเป็นสตริงที่ไม่ซ้ำกัน แต่ไม่ใช่ค่าว่างแต่ค่าอาจเป็นอะไรก็ได้
4.2. การสร้าง JSON จากแผนที่
แทนที่จะวางคีย์และค่าโดยตรงในJSONObjectเราสามารถสร้างที่กำหนดเองแผนที่แล้วผ่านมันเป็นอาร์กิวเมนต์ไปยังJSONObjectคอนสตรัค 's
ตัวอย่างนี้จะให้ผลลัพธ์เช่นเดียวกับด้านบน:
Map map = new HashMap(); map.put("name", "jon doe"); map.put("age", "22"); map.put("city", "chicago"); JSONObject jo = new JSONObject(map);
4.3. การสร้างJSONObjectจาก JSON String
ในการแยกวิเคราะห์สตริง JSON เป็นJSONObjectเราสามารถส่งสตริงไปยังตัวสร้าง
ตัวอย่างนี้จะให้ผลลัพธ์เช่นเดียวกับด้านบน:
JSONObject jo = new JSONObject( "{\"city\":\"chicago\",\"name\":\"jon doe\",\"age\":\"22\"}" );
ผ่านสตริงอาร์กิวเมนต์ต้องเป็น JSON ที่ถูกต้องมิฉะนั้นคอนสตรัคนี้อาจโยนJSONException
4.4. อนุกรม Java Object เป็น JSON
หนึ่งในตัวสร้างของJSONObjectใช้ POJO เป็นอาร์กิวเมนต์ ในตัวอย่างด้านล่างแพ็กเกจใช้ getters จากคลาสDemoBeanและสร้างJSONObjectที่เหมาะสมสำหรับสิ่งเดียวกัน
To get a JSONObject from a Java Object, we'll have to use a class that is a valid Java Bean:
DemoBean demo = new DemoBean(); demo.setId(1); demo.setName("lorem ipsum"); demo.setActive(true); JSONObject jo = new JSONObject(demo);
The JSONObject jo for this example is going to be:
{"name":"lorem ipsum","active":true,"id":1}
Although we have a way to serialize a Java object to JSON string, there is no way to convert it back using this library.
If we want that kind of flexibility, we can switch to other libraries such as Jackson.
5. JSONArray
A JSONArray is an ordered collection of values, resembling Java's native Vector implementation.
- Values can be anything from a Number, String, Boolean, JSONArray, JSONObject or even a JSONObject.NULL object
- It's represented by a String wrapped within Square Brackets and consists of a collection of values separated by commas
- Like JSONObject, it has a constructor that accepts a source String and parses it to construct a JSONArray
The following are the primary methods of the JSONArray class:
- get(int index) – returns the value at the specified index(between 0 and total length – 1), otherwise throws a JSONException
- opt(int index) – returns the value associated with an index (between 0 and total length – 1). If there's no value at that index, then a null is returned
- put(Object value) – append an object value to this JSONArray. This method is overloaded and supports a wide range of data types
For a complete list of methods supported by JSONArray, visit the official documentation.
5.1. Creating JSONArray
Once we've initialized a JSONArray object, we can simply add and retrieve elements using the put() and get() methods:
JSONArray ja = new JSONArray(); ja.put(Boolean.TRUE); ja.put("lorem ipsum"); JSONObject jo = new JSONObject(); jo.put("name", "jon doe"); jo.put("age", "22"); jo.put("city", "chicago"); ja.put(jo);
Following would be contents of our JSONArray(code is formatted for clarity):
[ true, "lorem ipsum", { "city": "chicago", "name": "jon doe", "age": "22" } ]
5.2. Creating JSONArray Directly from JSON String
Like JSONObject the JSONArray also has a constructor that creates a Java object directly from a JSON String:
JSONArray ja = new JSONArray("[true, \"lorem ipsum\", 215]");
This constructor may throw a JSONException if the source String isn't a valid JSON String.
5.3. Creating JSONArray Directly from a Collection or an Array
The constructor of JSONArray also supports collection and array objects as arguments.
We simply pass them as an argument to the constructor and it will return a JSONArray object:
List list = new ArrayList(); list.add("California"); list.add("Texas"); list.add("Hawaii"); list.add("Alaska"); JSONArray ja = new JSONArray(list);
Now our JSONArray consists of:
["California","Texas","Hawaii","Alaska"]
6. JSONTokener
A JSONTokener takes a source String as input to its constructor and extracts characters and tokens from it. It's used internally by classes of this package (like JSONObject, JSONArray) to parse JSON Strings.
There may not be many situations where we'll directly use this class as the same functionality can be achieved using other simpler methods (like string.toCharArray()):
JSONTokener jt = new JSONTokener("lorem"); while(jt.more()) { Log.info(jt.next()); }
Now we can access a JSONTokener like an iterator, using the more() method to check if there are any remaining elements and next() to access the next element.
The tokens received from the previous example will be:
l o r e m
7. CDL
We're provided with a CDL (Comma Delimited List) class to convert comma delimited text into a JSONArray and vice versa.
7.1. Producing JSONArray Directly from Comma Delimited Text
In order to produce a JSONArray directly from the comma-delimited text, we can use the static method rowToJSONArray() which accepts a JSONTokener:
JSONArray ja = CDL.rowToJSONArray(new JSONTokener("England, USA, Canada"));
Our JSONArray now consists of:
["England","USA","Canada"]
7.2. Producing Comma Delimited Text from JSONArray
In order to reverse of the previous step and get back the comma-delimited text from JSONArray, we can use:
JSONArray ja = new JSONArray("[\"England\",\"USA\",\"Canada\"]"); String cdt = CDL.rowToString(ja);
The Stringcdt now contains:
England,USA,Canada
7.3. Producing JSONArray of JSONObjects Using Comma Delimited Text
To produce a JSONArray of JSONObjects, we'll use a text String containing both headers and data separated by commas.
The different lines are separated using a carriage return (\r) or line feed (\n).
The first line is interpreted as a list of headers and all the subsequent lines are treated as data:
String string = "name, city, age \n" + "john, chicago, 22 \n" + "gary, florida, 35 \n" + "sal, vegas, 18"; JSONArray result = CDL.toJSONArray(string);
The object JSONArray result now consists of (output formatted for the sake of clarity):
[ { "name": "john", "city": "chicago", "age": "22" }, { "name": "gary", "city": "florida", "age": "35" }, { "name": "sal", "city": "vegas", "age": "18" } ]
Notice that in this example, both data and header were supplied within the same String.There's an alternative way of doing this where we can achieve the same functionality by supplying a JSONArray that would be used to get the headers and a comma-delimited String working as the data.
Different lines are separated using a carriage return (\r) or line feed (\n):
JSONArray ja = new JSONArray(); ja.put("name"); ja.put("city"); ja.put("age"); String string = "john, chicago, 22 \n" + "gary, florida, 35 \n" + "sal, vegas, 18"; JSONArray result = CDL.toJSONArray(ja, string);
Here we'll get the contents of object result exactly as before.
8. Cookie
The Cookie class deals with web browser cookies and has methods to convert a browser cookie into a JSONObject and vice versa.
Here are the main methods of the Cookie class:
- toJsonObject(String sourceCookie) – converts a cookie string into a JSONObject
- toString(JSONObject jo) – this is reverse of the previous method, converts a JSONObject into a cookie String.
8.1. Converting a Cookie String into a JSONObject
To convert a cookie String to a JSONObject, well use the static method Cookie.toJSONObject():
String cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/"; JSONObject cookieJO = Cookie.toJSONObject(cookie);
8.2. Converting a JSONObject into Cookie String
Now we'll convert a JSONObject into cookie String. This is reverse of the previous step:
String cookie = Cookie.toString(cookieJO);
9. HTTP
The HTTP class contains static methods that are used to convert HTTP headers to JSONObject and vice versa.
This class also has two main methods:
- toJsonObject(String sourceHttpHeader) – converts a HttpHeader String to JSONObject
- toString(JSONObject jo) – converts the supplied JSONObject to String
9.1. Converting JSONObject to HTTP Header
HTTP.toString() method is used to convert a JSONObject to HTTP header String:
JSONObject jo = new JSONObject(); jo.put("Method", "POST"); jo.put("Request-URI", "//www.example.com/"); jo.put("HTTP-Version", "HTTP/1.1"); String httpStr = HTTP.toString(jo);
Here, our String httpStr will consist of:
POST "//www.example.com/" HTTP/1.1
Note that while converting an HTTP request header, the JSONObject must contain “Method”,“Request-URI” and “HTTP-Version” keys, whereas, for response header, the object must contain “HTTP-Version”,“Status-Code” and “Reason-Phrase” parameters.
9.2. Converting HTTP Header String Back to JSONObject
Here we will convert the HTTP string that we got in the previous step back to the very JSONObject that we created in that step:
JSONObject obj = HTTP.toJSONObject("POST \"//www.example.com/\" HTTP/1.1");
10. JSONException
The JSONException is the standard exception thrown by this package whenever any error is encountered.
ใช้กับทุกคลาสจากแพ็คเกจนี้ โดยปกติข้อยกเว้นจะตามมาด้วยข้อความที่ระบุสิ่งที่ผิดพลาด
11. บทสรุป
ในบทช่วยสอนนี้เราดู JSON โดยใช้ Java - org.json - และเรามุ่งเน้นไปที่ฟังก์ชันหลักบางอย่างที่มีอยู่ที่นี่
ข้อมูลโค้ดทั้งหมดที่ใช้ในบทความนี้สามารถพบได้ใน GitHub