通过休息Web服务调用反序列化json字符串时出错

时间:2012-06-27 07:00:35

标签: json web-services rest gson

有一个webservise以json的形式返回appfuse用户实例,其中此用户模型包含属性角色,这是一组角色对象。 我的问题是,当这个角色属性不包含角色对象或多个角色对象时,它可以正常工作,但是当它包含单个角色元素时,它不起作用

异常::

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 218
   at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:180)
   at com.google.gson.Gson.fromJson(Gson.java:755)
   at com.google.gson.Gson.fromJson(Gson.java:721)
   at com.google.gson.Gson.fromJson(Gson.java:670)
   at com.google.gson.Gson.fromJson(Gson.java:642)
   at com.steriamobile.ws.smfserver.service.SMFUserServiceImpl.getUser(SMFUserServiceImpl.java:44)
   at com.steriamobile.ws.smfserver.service.SMFUserManagerImpl.getUser(SMFUserManagerImpl.java:19)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
   at java.lang.reflect.Method.invoke(Method.java:597)
   at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307)
   at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)
   at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
   at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106)
   at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
   at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89)
   at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
   at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
   at $Proxy32.getUser(Unknown Source)

REST服务::

 @GET
@Path("/getUser/{id}")
public User get(@PathParam("id") Long id) {
    return userManager.get(id);
}

反序列化代码:

Gson gson = new Gson();     
User user = gson.fromJson(json,new TypeToken<User>() {}.getType());

1 个答案:

答案 0 :(得分:1)

正如我理解问题描述一样,自定义反序列化对于处理JSON有时是数组而有时是对象的情况是必要的。

以前的StackOverflow线程(例如Parsing JSON with GSON, object sometimes contains list sometimes contains objectGson handle object or array)已经介绍了如何使用Gson来处理此特定问题。