Java Gson 预期为 BEGIN_ARRAY,但在第 1 行第 62 列处为 STRING

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16380367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:35:02  来源:igfitidea点击:

Gson Expected BEGIN_ARRAY but was STRING at line 1 column 62

javajsongsonarrays

提问by Liam Potter

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 :

这段代码应该解析 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:

JSON 是:

{
  "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

我得到的错误是: Expected BEGIN_ARRAY but was STRING at line 1 column 62

But I have no idea why, the json is valid according to jsonlint.

但我不知道为什么,根据 jsonlint,json 是有效的。

Any idea on why I am getting this error?

关于为什么我收到此错误的任何想法?

采纳答案by Perception

Your JSON is valid - but your mapping class isn't (parts of it don't match). In particular, the filesproperty 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 guidewhen mapping between JSON structures and Java classes. This JSON:

您的 JSON 有效 - 但您的映射类无效(部分不匹配)。特别是,files您的类的属性不能Map<String, String>从给定的 JSON映射为 a 。很难在没有看到更大样本的情况下推荐用于存储数据的替代结构,但一般而言,在 JSON 结构和 Java 类之间进行映射时,您可以遵循本指南。这个 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:

表示包含对象的数组,其中每个对象最好表示为地图。所以本质上是一个地图列表。因此,您的 Java 对象应该是:

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.

请注意,我已通过将它们设为私有并添加 getter/setter 来更正您的属性。使用上面定义的类,您的程序应该可以正常工作。

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 CFSstructure though, you would need to manually parse the JSON into it.

如果您发现自己需要保留当前CFS结构,则需要手动将 JSON 解析为其中。

回答by rekire

As already Brain noted you have a array of objects so you need to convert this by your own with a custom deserializer.

正如 Brain 已经指出的那样,您有一个对象数组,因此您需要使用自定义反序列化器自行转换它。

Here is an example implementation:

这是一个示例实现:

public class q16380367 {
    final class CFS {
        public HashMap<String, String> files = new HashMap<String, String>();
        public ArrayList<String> directories = new ArrayList<String>();
    }

    public static void main(String[] args) {
        new q16380367();
    }

    public q16380367() {
        String JSON_STRING = "{\"directories\" : [\"folder1\", \"folder1/folder2\"], \"files\" : [{\"folder1\" : \"file.txt\"}, {\"folder1/folder2\" : \"file.cfg\"}]}";
        Gson gson = new GsonBuilder().registerTypeAdapter(
                new TypeToken<HashMap<String, String>>() {
                }.getType(), new CfsDeserializer()).create();
        CFS foo = gson.fromJson(JSON_STRING, CFS.class);
    }

    private final class CfsDeserializer implements
            JsonDeserializer<HashMap<String, String>> {
        @Override
        public HashMap<String, String> deserialize(JsonElement json,
                Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            HashMap<String, String> data = new HashMap<String, String>();
            JsonArray list = json.getAsJsonArray();
            for (JsonElement e : list) {
                Set<Entry<String, JsonElement>> entries = e.getAsJsonObject()
                        .entrySet();
                for (Entry<String, JsonElement> entry : entries) {
                    data.put(entry.getKey(), entry.getValue().getAsString());
                }
            }
            return data;
        }
    }
}

回答by Manthan_Admane

If someone is getting this error in AndroidStudio :

如果有人在 AndroidStudio 中收到此错误:

Try two things:

尝试两件事:

  1. Roll back to last working conditions. (Revert if you use VCS).
  2. In build options Clean project and rebuild. (Worked for me.)
  1. 回滚到上次工作状态。(如果您使用 VCS,则还原)。
  2. 在构建选项中清理项目并重建。(为我工作。)

I'm fairly new to android. Excuse any mistakes if committed. Suggestions are welcome :)

我对android相当陌生。如果犯了任何错误,请原谅。欢迎提出建议:)