我的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);
你的JS鱈魚e爲我生成有效的JSON。我把它粘貼到Chrome的控制檯,並採取了console.log(json)。 –