
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert JSON Object to/from a Cookie in Java
The JSON is one of the widely used data-interchange formats and is a lightweight and language independent. We can convert a JSONObject to cookie using the toString() method and convert a cookie to JSONObject using the toJSONObject() method of org.json.Cookie class.
Convert JSONObject to cookie
Syntax
public static java.lang.String toString(JSONObject jo) throws JSONException
Example
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); } }
Output
username=Adithya;expires=Thu, 07 May 2020 12:00:00 UTC;path=/
Convert cookie to JSONObject
Syntax
public static JSONObject toJSONObject(java.lang.String string) throws JSONException
Example
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); } }
Output
{"path":"/","expires":"Thu, 07 May 2020 12:00:00 UTC","name":"username","value":"Adithya"}
Advertisements