JSON là định dạng trao đổi dữ liệu phổ biến, nhẹ và độc lập ngôn ngữ. Chuyển JSONObject thành cookie dùng toString(), chuyển cookie thành JSONObject dùng toJSONObject() của class org.json.Cookie.
Chuyển JSONObject thành cookie
Cú pháp
public static java.lang.String toString(JSONObject jo) throws JSONException
Ví dụ
import org.json.Cookie; import org.json.JSONObject; public class JSONObjectToCookieTest { public static void main(String args[]) { JSONObject jsonObject = new JSONObject(); jsonObject.put("path", "/"); jsonObject.put("expires", "Thu, 07 May 2020 12:00:00 UTC"); jsonObject.put("name", "username"); jsonObject.put("value", "Adithya"); String cookie = Cookie.toString(jsonObject); System.out.println(cookie); } }
Kết quả
username=Adithya;expires=Thu, 07 May 2020 12:00:00 UTC;path=/
Chuyển cookie thành JSONObject
Cú pháp
public static JSONObject toJSONObject(java.lang.String string) throws JSONException
Ví dụ
import org.json.Cookie; import org.json.JSONObject; public class ConvertCookieToJSONObjectTest { public static void main(String args[]) { String cookie = "username=Adithya; expires=Thu, 07 May 2020 12:00:00 UTC; path=/"; JSONObject jsonObject = Cookie.toJSONObject(cookie); System.out.println(jsonObject); } }
Kết quả
{"path":"/","expires":"Thu, 07 May 2020 12:00:00 UTC","name":"username","value":"Adithya"}