在 Java 中如何将 JSONObject 转换为 cookie?
javajsonobject oriented programmingprogramming更新于 2025/7/17 9:16:17
JSON 是一种广泛使用的 数据交换 格式,是一种轻量级且语言独立的格式。我们可以使用 toString() 方法将 JSONObject 转换为 cookie,也可以使用 org.json.Cookie 类的 toJSONObject() 方法将 cookie 转换为 JSONObject。
将 JSONObject 转换为 cookie
语法
public static java.lang.String toString(JSONObject jo) throws JSONException
示例
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);
}
}
输出
username=Adithya;expires=Thu, 07 May 2020 12:00:00 UTC;path=/
将 cookie 转换为 JSONObject
语法
public static JSONObject toJSONObject(java.lang.String string) throws JSONException
示例
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);
}
}
输出
{"path":"/","expires":"Thu, 07 May 2020 12:00:00 UTC","name":"username","value":"Adithya"}
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

