0

例外:

**org.springframework.http.converter.HttpMessageNotReadableExeption:
Could not read JSON:java.lang.IllegalStateExeption:
Exepted BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2;
nested exception in com.google.gson.JsonSyntaxException:java**

JSON:

{
    "objects": [
        {
            "id": "1",
            "category": "category1"
        },
        {
            "id": "2",
            "category": "category2"
        }
    ]
}

API 呼び出し:

HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "json")));

HttpEntity << ? > requestEntity = new HttpEntity < Object > (requestHeaders);
GsonHttpMessageConverter messageConverter = new GsonHttpMessageConverter();
List < HttpMessageConverter << ? >> messageConverters = new ArrayList < HttpMessageConverter << ? >> ();

messageConverters.add(messageConverter);
RestTemplate restTemplate = new RestTemplate();

restTemplate.getMessageConverters().add(messageConverter);
restTemplate.getMessageConverters().add(new org.springframework.http.converter.json.GsonHttpMessageConverter());

ResponseEntity < Category[] > responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Category[].class);
Category[] response = responseEntity.getBody();

モデルクラス:

public class Category {

     private Integer id;
     private String category;

     public Category() {}

     public Integer getId() {
         return id;
     }
     public void setId(Integer newId) {
         this.id = newId;
     }

     public String getCategory() {
         return category;
     }

     public void setCategory(String category) {
         this.category = category;
     }
 }

ログキャット:

12-07 02:55:21.123: E/Trace(1043): error opening trace file: No such file or directory (2)
12-07 02:55:22.693: D/libEGL(1043): loaded /system/lib/egl/libEGL_emulation.so
12-07 02:55:22.702: D/(1043): HostConnection::get() New Host Connection established 0x2a0d9c80, tid 1043
12-07 02:55:22.723: D/libEGL(1043): loaded /system/lib/egl/libGLESv1_CM_emulation.so
12-07 02:55:22.754: D/libEGL(1043): loaded /system/lib/egl/libGLESv2_emulation.so
12-07 02:55:22.903: W/EGL_emulation(1043): eglSurfaceAttrib not implemented
12-07 02:55:22.963: D/OpenGLRenderer(1043): Enabling debug mode 0
12-07 02:55:23.363: D/dalvikvm(1043): GC_CONCURRENT freed 231K, 6% free 6196K/6535K, paused 76ms+41ms, total 284ms
12-07 02:57:16.873: W/EGL_emulation(1043): eglSurfaceAttrib not implemented 12-07 02:57:20.872: D/dalvikvm(1043): null clazz in OP_INSTANCE_OF, single-stepping
4

1 に答える 1

1

これを試してみてください。結果は配列であり、json オブジェクトではありません。

[
    {
        "id": "1",
        "kategorija": "kategorija1"
    },
    {
        "id": "2",
        "kategorija": "kategorija2"
    }
]

そうすれば、配列を持つ json オブジェクトではなく、json オブジェクトの配列を受け取ることができます。

于 2012-12-07T15:21:00.437 に答える