0

Here is my code

Gson gson = new Gson();
HashMap<String, String> map = new HashMap<>();
map = gson.fromJson(new FileReader(inputFile), map.getClass());

The content of the inputFile is

{
  "key1": "[\"value1\"]",
  "key2": "value2"
}

When I inspect the value of map.get("key2") during debugging in Eclipse, the value is actually (java.util.ArrayList<E>) [value1]

How can I make Gson deserialize the content to

{key1="[value1]", key2=value2}

Thanks

0

1 Answer 1

1

I feel like you are seeing the HashMap#toString() output of

{key1=["value1"], key2=value2}

and thinking that

["value1"] 

is a List of some type, containing a String value of "value1".

It isn't. Your String, as a String literal, would be represented as "[\"value1\"]". Its value is ["value1"]. That's what gets displayed.

Both your JSON key-value entries are string-string and will get converted as such.

"key1": "[\"value1\"]",
//      ^ indicates a JSON string
Sign up to request clarification or add additional context in comments.

2 Comments

The test code snippet I tried also worked, regardless of loading the source String from file or variable in memory. The complete case is I have some other code that down loads the file from S3 and return me a File object. I would get this deserialization error if I do not write the File to a local file. After writing the file locally and reopening the local file with FileReader and passing it to the fromJson method, everything is working as expected.
@derrdji So was it just an interpretation problem or something else?

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.