Gson 预期为 BEGIN_ARRAY,但在第 1 行第 62 列处为 STRING [英] Gson Expected BEGIN_ARRAY but was STRING at line 1 column 62
问题描述
我有以下课程:
final class CFS {
public Map<String, String> files = new HashMap<String, String>();
public List<String> directories = new ArrayList<String>();
}
这段代码应该解析json:
And this code which should parse the json :
CFS cfs = JStorage.getGson().fromJson(JSON_STRING, CFS.class);
哪里
JSON_STRING = "{\"directories\" : [\"folder1\", \"folder1/folder2\"], \"files\" : [{\"folder1\" : \"file.txt\"}, {\"folder1/folder2\" : \"file.cfg\"}]}"
JSON 是:
{
"directories": ["folder1", "folder1/folder2"],
"files": [
{
"folder1": "file.txt"
},
{
"folder1/folder2": "file.cfg"
}
]
}
我得到的错误是:预期为 BEGIN_ARRAY 但在第 1 行第 62 列处为 STRING
但我不知道为什么,json 根据 jsonlint 是有效的.
But I have no idea why, the json is valid according to jsonlint.
知道为什么我会收到此错误吗?
Any idea on why I am getting this error?
推荐答案
您的 JSON 有效 - 但您的映射类无效(部分不匹配).特别是,您的类的 files
属性无法从给定的 JSON 映射为 Map
.很难在没有看到更大样本的情况下推荐用于存储数据的替代结构,但通常您可以在以下情况下遵循本指南JSON 结构和 Java 类之间的映射.这个 JSON:
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"
}
]
表示一个包含对象的数组,其中每个对象最好表示为一个映射.所以本质上是一个地图列表.因此,您的 Java 对象应该是:
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
}
请注意,我已通过将它们设为私有并添加 getter/setter 来更正您的属性.使用上面定义的类,您的程序应该可以正常工作.
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());
产生:
[{folder1=file.txt}, {folder1/folder2=file.cfg}]
如果您发现自己需要保留当前的 CFS
结构,则需要手动将 JSON 解析到其中.
If you find yourself needing to retain the current CFS
structure though, you would need to manually parse the JSON into it.
这篇关于Gson 预期为 BEGIN_ARRAY,但在第 1 行第 62 列处为 STRING的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!