Gson解析出现类似错误,com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_AR

<span style="font-size:18px;">Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 45
	at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
	at com.google.gson.Gson.fromJson(Gson.java:803)
	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 GsonUtils.changeGsonToBean(GsonUtils.java:22)
	at Test.main(Test.java:25)
Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 45
	at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:338)
	at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:79)
	at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60)
	at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
	at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)
	... 6 more</span>

类似这种错误的原因,Expected BEGIN_ARRAY but was STRING at line 1 column 45.

可以看到提示大概的意思就是,期望是BEGIN_ARRAY,但是是STRING。


下面是例子:

<span style="font-size:18px;">import java.io.Serializable;
import java.util.List;


public class Test {
	public static List<ArticleImage> articleimglist;
	public static void main(String[] args) {
		String str = "{\"age\":23,\"name\":\"dsfds\", <span style="background-color: rgb(255, 102, 102);">\"articleimglist\":\"\"</span>}";
		Article ar = GsonUtils.changeGsonToBean(str, Article.class);
		System.out.println(ar.age);
		System.out.println(ar.name);
		
	}
}

class Article {
	public int age;
	public String name;
	<span style="color:#ff6666;">public List<ArticleImage> articleimglist;</span>
}

class ArticleImage implements Serializable{
	private static final long serialVersionUID = 6762300101092577096L;
	public String image;
}</span>

可以看到本来是一个对象的数组,但是我这里确实"",空字符串。所以导致出现了问题。

其实这个问题是实际中遇到的,原因是服务器定义数据的时候不够严谨,将数组对象定义为空字符串了。

<span style="font-size:18px;">String str = "{\"age\":23,\"name\":\"dsfds\", <span style="background-color: rgb(255, 102, 102);">\"articleimglist\":null</span>}";</span>
<span style="font-size:18px;">这样子就可以了。</span>

总结:(1)碰到这个问题的时候,比较郁闷,使用HiJson等解析工具没有报错。但是实际代码中总是报错。(这个很坑,然自己一时没有想明白)

            (2)服务器端的数据类型应该定义严谨一些,要不然很容易出现错误。

            (3)Expected BEGIN_ARRAY but was STRING at line 1 column 45.以后碰到这种错误就大概知道是啥意思了。

                      找出这个问题的办法也是,分解法,实际项目中数据量很大,分解成小例子,就趁成上述的。


你可能感兴趣的:(Gson解析出现类似错误,com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_AR)