2013-01-16 22 views
1

我的JSON字符串時是:得到錯誤不是一個JSON陣列使用GSON

{ 
    "sigTemplateId": 1, 
    "name": "Test Ticket Template", 
    "groups": "[{\"sigTemplateId\": 1, \"sigTemplateGroupId\": 1, \"name\": \"Group 1\", \"ordinal\": 1}]" 
} 

這會從我的jsp到servlet發送。 Servlet代碼是:

Gson gson = new Gson(); 

if (jsonData != null) { 
    Type objType = new TypeToken<SigTemplateObj>() {}.getType(); 
    SigTemplateObj sigTemplateToSave = gson.fromJson(jsonData, objType); 
    //SigTemplateObj sigTemplateToSave = gson.fromJson(jsonData, SigTemplateObj.class); 
} 

我得到︰java.lang.IllegalStateException:這不是一個JSON數組。 gson試圖解析groups數組:JsonDeserializer [email protected]97未能反序列化json對象「[{\」sigTemplateId \「:1,\」sigTemplateGroupId \「:1,\」name \「 :\ 「組1 \」 \ 「序\」:1}]」是給定類型的java.util.ArrayList

我的對象的代碼是:

public class SigTemplateObj { 

    int sigTemplateId; 
    String dyninkName; 
    int dyninkFormId; 
    String name; 

    //children collections 
    ArrayList<SigTemplateFieldObj> fields; 
    ArrayList<SigTemplateGroupObj> groups; 
... 
} 

public class SigTemplateGroupObj { 
    int sigTemplateGroupId; 
    int sigTemplateId; 
    int ordinal; 
    String name; 
... 
} 

我試圖上述兩種代碼和這條線以及兩次獲得相同的結果。

SigTemplateObj sigTemplateToSave = gson.fromJson(jsonData, SigTemplateObj.class); 

任何幫助,將不勝感激。 謝謝, 埃裏克

現在我只是要解決我的javascript治療組數組的數組,而不是一個字符串:

var testObject = new Object(); 
     testObject.sigTemplateId = 1; 
     testObject.name = 'Test Ticket Template'; 
     testObject['groups'] = []; 
     var testGroup = new Object(); 
     testGroup.sigTemplateId = 1; 
     testGroup.sigTemplateGroupId = 1; 
     testGroup.name = 'Group 1'; 
     testGroup.ordinal = 1; 
     testObject.groups.push(testGroup); 

     var json = JSON.stringify(testObject); 
+0

你的JS鱈魚e爲我生成有效的JSON。我把它粘貼到Chrome的控制檯,並採取了console.log(json)。 –

回答

2

該組陣列是不是一個數組,而是一個字符串:

"groups": "..." 

試試這個JSON來代替:

{ 
    "sigTemplateId": 1, 
    "name": "Test Ticket Template", 
    "groups": [{"sigTemplateId": 1, "sigTemplateGroupId": 1, "name": "Group 1", "ordinal": 1}] 
} 
+0

我改變了我的字符串,並工作,但我將如何更改我的JavaScript,以便它不把它當作字符串,但作爲一個數組? – Eric

+0

Javascript:var testObject = new Object(); testObject.sigTemplateId = 1; testObject.name ='Test Ticket Template'; testObject ['groups'] = []; var testGroup = new Object(); testGroup.sigTemplateId = 1; testGroup.sigTemplateGroupId = 1; testGroup.name ='Group 1'; testGroup.ordinal = 1; testObject.groups.push(testGroup); var json = JSON.stringify(testObject); – Eric

+1

請更新你的問題,並在那裏插入你的JS代碼。並將javascript標籤添加到您的問題。 –