0

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.

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]

2 Answers 2

1

It's because you're trying to create an ArrayList of String, but you have OBJECTS, not strings in your 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.

Sign up to request clarification or add additional context in comments.

2 Comments

You would think it would at least attempt to do Object.toString
thank you. I had played arround with the function and forgot to change String back to ChatMessage
0
  1. Your database string is missing a JSON array closing bracket ] at the end.

  2. gson type parameter is wrong. You require a ArrayList<ChatMessage> but you used ArrayList<String>.

Replace

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

With

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.