简体   繁体   中英

Expected BEGIN_OBJECT but was STRING in Gson

Hi I am try to parse some JSON by GSON which used number as the key. I reference the post but it give some error and I don't know why.

How to convert json objects with number as field key in Java?

I also see the post but still cannot solve my problem.

"Expected BEGIN_OBJECT but was STRING at line 1 column 1"

在此处输入图片说明

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Gson gson = new Gson();

        Type type = new TypeToken<HashMap<String, HashMap<String, String>>>() {}.getType();
        Map<String, Map<String, String>> map = gson.fromJson("./src/main/resources/input.json", type);

    }
}

The json file is

{
  "1":{"id":"1"}
}

The fromJson method doesn't receive a filename, it receives an actual JSON: look at the docs here

But there is an overload that receives a Reader instead:

try (FileReader reader = new FileReader("./src/main/resources/input.json"))
{
    map = gson.fromJson(reader, type)
}
catch (...) { ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM