Convert JSONObject to/from a cookie in Java?

JavaJSONObject Oriented ProgrammingProgramming

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"}
raja
Published on 15-Oct-2019 12:42:50
Advertisements