如何将 JSON 数组转换为 ArrayList?

杰森·史密斯

我从一个看起来像这样的数据库中抓取一个字符串

[{"messageContent":"Good morning Christine! My name is Oso, it\u0027s 
beary nice to meet you 
:3","msgType":"MSG_TYPE_RECEIVED","statusCode":0,"timeString":"10:31"}, 
{"messageContent":"Good morning Christine! My name is Oso, it\u0027s 
beary nice to meet you 
:3","msgType":"MSG_TYPE_RECEIVED","statusCode":0,"timeString":"10:31"}

它以 ArrayList 开始,但我必须将其转换为字符串以存储在数据库中。

我需要把它转换回来。我本来打算使用这个功能,但它似乎不起作用。

public static ArrayList<ChatMessage> fromString(String value) {
    Type listType = new TypeToken<ArrayList<String>>() {}.getType();
    return new Gson().fromJson(value, listType);
}

当我尝试运行该函数时出现此错误。

 com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 3 path $[0]
武科

这是因为您正在尝试创建ArrayListof String,但是您的 JSON 中有 OBJECTS,而不是字符串。尝试更改此行:

Type listType = new TypeToken<ArrayList<String>>() {}.getType();

对于这样的事情:

Type listType = new TypeToken<ArrayList<ChatMessage>>() {}.getType();

假设Gson知道如何反序列化您的ChatMessage类,那应该可行。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章