gpt4 book ai didi

java - 如何将 ArrayList 的字符串表示形式转换为 ArrayList

转载 作者:行者123 更新时间:2023-12-01 16:34:55 25 4
gpt4 key购买 nike

我有一个 ArrayList,我将其转换为字符串

ArrayList str = (ArrayList) retrieveList.get(1);
...

makeCookie("userCredentialsCookie", str.toString(), httpServletResponce);
....

private void makeCookie(String name, String value, HttpServletResponse response) {

Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
response.addCookie(cookie);

} //end of makeCookie()

现在,当我检索 cookie 值时,我得到 String,但我再次想将其转换为 ArrayList,例如

private void addCookieValueToSession(HttpSession session, Cookie cookie, String attributeName) {       
if (attributeName.equalsIgnoreCase("getusercredentials")) {

String value = cookie.getValue();
ArrayList userCredntialsList = (ArrayList)value; //Need String to ArrayList
session.setAttribute(attributeName, userCredntialsList);
return;
}

String value = cookie.getValue();
session.setAttribute(attributeName, value);

} //end of addCookieValueToSession

如何再次将其转换为 ArrayList?谢谢。

最佳答案

someList.toString() 不是序列化数据的正确方法,并且会给您带来麻烦。

由于您需要将其作为字符串存储在 cookie 中,因此请使用 JSON 或 XML。 google-gson可能对你来说是一个很好的库:

ArrayList str = (ArrayList) retrieveList.get(1);
String content = new Gson().toJson(str);
makeCookie("userCredentialsCookie", content, httpServletResponce);
//...
ArrayList userCredntialsList = new Gson().fromJson(cookie.getValue(), ArrayList.class);

关于java - 如何将 ArrayList 的字符串表示形式转换为 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10186220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com