[英]How do I convert a JSON array to an ArrayList?
I am grabbing a string from a database that looks like this 我从一个看起来像这样的数据库中获取一个字符串
[{"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"}
It began as an ArrayList but I had to convert it into a string to store in in the database. 它以ArrayList开头,但是我必须将其转换为字符串以存储在数据库中。
I need to convert it back. 我需要将其转换回去。 I had was going to use this function but it doesn't seem to work.
我本来打算使用此功能,但似乎不起作用。
public static ArrayList<ChatMessage> fromString(String value) {
Type listType = new TypeToken<ArrayList<String>>() {}.getType();
return new Gson().fromJson(value, listType);
}
I get this error when I try to run the function. 当我尝试运行该函数时出现此错误。
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 3 path $[0]
It's because you're trying to create an ArrayList
of String
, but you have OBJECTS, not strings in your JSON. 这是因为您尝试创建
String
的ArrayList
,但是您拥有对象,而不是JSON中的字符串。 Try changing this line: 尝试更改此行:
Type listType = new TypeToken<ArrayList<String>>() {}.getType();
To something like this: 对于这样的事情:
Type listType = new TypeToken<ArrayList<ChatMessage>>() {}.getType();
Assuming Gson
knows how to deserialize your ChatMessage
class, that should work. 假设
Gson
知道如何反序列化ChatMessage
类,那应该可以工作。
Your database string is missing a JSON array closing bracket ]
at the end. 您的数据库字符串末尾缺少JSON数组右括号[
]
。
gson
type parameter is wrong. gson
类型参数错误。 You require a ArrayList<ChatMessage>
but you used ArrayList<String>
. 您需要一个
ArrayList<ChatMessage>
但是您使用了ArrayList<String>
。
Replace 更换
Type listType = new TypeToken<ArrayList<String>>() {}.getType();
With 同
Type listType = new TypeToken<ArrayList<ChatMessage>>() {}.getType();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.