简体   繁体   中英

Gson: JsonSyntaxException: Expected BEGIN_OBJECT but was STRING

I am trying to convert a JSON String into a HashMap. Here is some of my code:

public static void createSimpleAppointment(String json){
try
    {
    Gson gson = new Gson();
    HashMap<String,String> data = new HashMap<String,String>();
    data = gson.fromJson(json, data.getClass());

The exception is being thrown on the last of those lines (where I set data).

The JSON String is

{"body": "body", "startDate": "2014-05-30 11:00:00", "endDate": "2014-05-30 12:00:00", "location": "location", "subject": "subject!"}

The exception I get is

Exception in thread "main" java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58) Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 3 at com.google.gson.Gson.fromJson(Gson.java:815) at com.google.gson.Gson.fromJson(Gson.java:768) at com.google.gson.Gson.fromJson(Gson.java:717) at com.google.gson.Gson.fromJson(Gson.java:689) at ews.calendar.Calendar.createSimpleAppointment(Calendar.java:70) at ews.main.gateway.Main.main(Main.java:34) ... 5 more Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 3 at com.g oogle.gson.stream.JsonReader.beginObject(JsonReader.java:374) at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:183) at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:145) at com.google.gson.Gson.fromJson(Gson.java:803) ... 10 more

You can convert the JSON string into Java POJO class as well. The name of instance member in POJO class should be exactly same ( case-sensitive ) as defined in JSON string.

You don't need to convert the date string to date object that is handled by GsonBuilder#setDateFormat() method by default.

Sample code:

class MyJSONObject {
    private String body;
    private Date startDate;
    private Date endDate;
    private String location;
    private String subject;
    // getter & setter
}

// convert json string to MyJSONObject 
MyJSONObject data = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
                              .create().fromJson(jsonString, MyJSONObject.class);

// pretty printing of JSON string back from POJO class object
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));

output:

{
    "body": "body",
    "startDate": "May 30, 2014 11:00:00 AM",
    "endDate": "May 30, 2014 12:00:00 PM",
    "location": "location",
    "subject": "subject!"
}

我没有得到你用Gson 2.2.4报告的异常,但是你应该开始使用TypeToken用于泛型类型。

HashMap<String, String> data = gson.fromJson(json, new TypeToken<HashMap<String, String>>() {}.getType());

该错误可能有点误导 - 在我的情况下,它是LocalDateTime缺少的Deserializer ,并且在第一个日期失败。

I had a Map within a class that was to be json-ed and the same error as described above:

public class Setting implements Serializable {
private Map<Key, Double> keyToValue = new HashMap<>();

// other fields, setters and getters...

public Map<Key, Double> getKeyToValue() {
        return keyToValue;
    }
public void setKeyToValue(Map<PlantKey, Double> keyToValue) {
        this.keyToValue = keyToValue;
    }
}

I had to use the following to make it work:

GsonBuilder builder = new GsonBuilder();
builder.enableComplexMapKeySerialization();
builder.create();

Source: https://github.com/google/gson/issues/478

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