I have the following class :
final class CFS {
public Map<String, String> files = new HashMap<String, String>();
public List<String> directories = new ArrayList<String>();
}
And this code which should parse the json :
CFS cfs = JStorage.getGson().fromJson(JSON_STRING, CFS.class);
Where
JSON_STRING = "{\"directories\" : [\"folder1\", \"folder1/folder2\"], \"files\" : [{\"folder1\" : \"file.txt\"}, {\"folder1/folder2\" : \"file.cfg\"}]}"
JSON is:
{
"directories": ["folder1", "folder1/folder2"],
"files": [
{
"folder1": "file.txt"
},
{
"folder1/folder2": "file.cfg"
}
]
}
The error I'm getting is: Expected BEGIN_ARRAY but was STRING at line 1 column 62
But I have no idea why, the json is valid according to jsonlint.
Any idea on why I am getting this error?
If someone is getting this error in AndroidStudio :
Try two things:
I'm fairly new to android. Excuse any mistakes if committed. Suggestions are welcome :)
Your JSON is valid - but your mapping class isn't (parts of it don't match). In particular, the files
property of your class cannot be mapped as a Map<String, String>
from the given JSON. It's hard to recommend an alternate structure for storing the data without seeing a larger sample, but in general you can follow this guide when mapping between JSON structures and Java classes. This JSON:
"files": [
{
"folder1": "file.txt"
},
{
"folder1/folder2": "file.cfg"
}
]
represents an array containing objects, where each object is best represented as a map. So in essence, a list of maps. Consequently your Java object should be:
public class CFS {
private List<Map<String, String>> files = new ArrayList<Map<String, String>>(
4);
private List<String> directories = new ArrayList<String>(4);
// Constructors, setters/getters
}
Note that I've corrected your properties by making them private and adding getters/setters. With the above defined class your program should work just fine.
final Gson gson = new GsonBuilder().create();
final CFS results = gson.fromJson(json, CFS.class);
Assert.assertNotNull(results);
Assert.assertNotNull(results.getFiles());
System.out.println(results.getFiles());
Produces:
[{folder1=file.txt}, {folder1/folder2=file.cfg}]
If you find yourself needing to retain the current CFS
structure though, you would need to manually parse the JSON into it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With