为了账号安全,请及时绑定邮箱和手机立即绑定

为什么来自Json的GSON抛出一个JsonSyntaxException

为什么来自Json的GSON抛出一个JsonSyntaxException

德玛西亚99 2019-06-10 16:49:07
为什么来自Json的GSON抛出一个JsonSyntaxException我试图将一些JSON内容反序列化为一个自定义POJO类型Gson#fromJson(String, Class).这段代码import com.google.gson.Gson;public class Sample {     public static void main(String[] args) {         String json = "{\"nestedPojo\":[{\"name\":null, \"value\":42}]}";         Gson gson = new Gson();         gson.fromJson(json, Pojo.class);     }}class Pojo {     NestedPojo nestedPojo;}class NestedPojo {     String name;     int value;}抛出以下异常Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:  Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 16 path $.nestedPojo     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:200)     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:103)     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:196)     at com.google.gson.Gson.fromJson(Gson.java:810)     at com.google.gson.Gson.fromJson(Gson.java:775)     at com.google.gson.Gson.fromJson(Gson.java:724)     at com.google.gson.Gson.fromJson(Gson.java:696)     at com.example.Sample.main(Sample.java:23)Caused by: java.lang.IllegalStateException:      Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 16 path $.nestedPojo     at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:387)     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:189)     ... 7 more为什么gson不能正确地将我的JSON文本转换为我的POJO类型?
查看完整描述

2 回答

?
一只名叫tom的猫

TA贡献1906条经验 获得超3个赞

class Pojo {
  NestedPojo nestedPojo;}

在json中有一个nestedpojo数组,所以要么更改代码

  NestedPojo[] nestedPojo;

或者更改json字符串。

String json = "{\"nestedPojo\":{\"name\":null, \"value\":42}}";


查看完整回答
反对 回复 2019-06-10
  • 2 回答
  • 0 关注
  • 8391 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号