gpt4 book ai didi

java - 将 Json 转换为列表

转载 作者:搜寻专家 更新时间:2023-10-30 19:42:44 25 4
gpt4 key购买 nike

我正在尝试读取 Json 对象并将其写入我的数据库,但我不知道如何将从数据库中获取的字符串转换为字符串,以及稍后如何使用它 tp 将更改后的列表写回我的再次数据库。

所以当我向数据库询问我想要的字段时,我得到了这个字符串:

["[\"pw1\",\"pw2\",\"pw3\"]"]

然后我去创建我的类 LastPasswords

的对象
List<String> passwordList = (List<String>) controllerServlet.getMacroDatabaseManager().executeNativeQuery(queryGet);
LastPasswords lastPasswords = new LastPasswords(passwordList);
Gson gson = new Gson();
String Json = gson.toJson(lastPasswords);

这是 LastPasswords

public class LastPasswords {

private List<String> passwords;

public LastPasswords(List<String> passwords) {
this.passwords = passwords;
}

public List<String> getPasswords(){
return passwords;
}
public void setPasswords(List<String> passwords){
this.passwords = passwords;
}
}

然后当我有这个 json 字符串时,我尝试将它作为列表获取,但我没有获取列表。

lastPasswords.setPasswords((List<String>) gson.fromJson(banana, LastPasswords.class));
passwordList = lastPasswords.getPasswords();

感谢您的帮助。

最佳答案

您可以使用 com.google.gson.reflect.TypeToken.TypeToken 来定义 fromJson 方法的返回类型。然后,有了列表后,您可以创建一个新的 LastPasswords 来使用。

    String json = "[\"pw1\",\"pw2\",\"pw3\"]";
Gson gson = new Gson();
List<String> list = gson.fromJson(json, new TypeToken<List<String>>() {}.getType());
System.out.println(list.size());
System.out.println(list);

Output:
3
[pw1, pw2, pw3]

关于java - 将 Json 转换为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41139797/

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