이전 버전과 호환되는 방식으로 수업을 저장하기 위해 Gson을 사용하고 있습니다. 직렬화하려는 다음 싱글 톤 클래스가 있습니다.
public class DataHandler implements Serializable {
private static DataHandler instance; //SINGLETON
private HashMap<FormIdentification, BaseForm> forms =
new HashMap<FormIdentification, BaseForm>();
public void read(){
//read the json string
Gson gson = new Gson();
instance = gson.fromJson(json, DataHandler.class);
}
public void write(){
Gson gson = new Gson();
String json = gson.toJson(instance);
//write the json string
}
}
public class FormIdentification implements Serializable{
public String name, type;
byte[] id;
public FormIdentification(String name, String type, byte[] id) {
this.name = name;
this.type = type;
this.id = id;
}
}
public abstract class BaseForm implements Serializable{
protected FormIdentification identity;
protected final List<BaseQuestion> questions = new ArrayList<BaseQuestion>();
protected final HashMap<String, List<String>> personalData = new HashMap<String, List<String>>();
}
public class LinearForm extends BaseForm {
private DefaultMutableTreeNode criteria;
}
public abstract class BaseQuestion implements Serializable{
protected String question;
protected List<String> possibleAnswers;
}
다음 json으로 직렬화됩니다.
{
"forms":{
"test.Structures.FormIdentification@7b875faa":{
"criteria":{
"allowsChildren":true
},
"identity":{
"name":"Mircea",
"type":"linear",
"id":[
111,
119
]
},
"questions":[
],
"personalData":{
"Nume":[
]
}
}
}
}
json은 완전하며 생성 될 때 클래스에 포함 된 모든 데이터를 가지고 있습니다. 그러나 역 직렬화하려고 할 때 다음 오류가 발생합니다.
SEVERE: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 12
압축 형식이므로 1 행 12 열은 { "forms": { "test.Structures ..."여야합니다.
저는 json을 처음 사용하여 솔루션을 찾기 시작했지만 솔루션을 찾지 못했습니다. TypeToken을 사용하여 캐스팅을 시도했고 사용자 지정 serializer를 작성해 보았지만 관리하지 않았습니다. 또한 "forms"변수 만 직렬화하려고 시도했지만 동일한 오류가 발생합니다.
JSON 객체는 키 / 값 쌍의 모음입니다. 값은 JSON 값 (문자열, 숫자, 개체, 배열, true, false 또는 null)이 될 수 있습니다. 그러나 JSON 개체의 키는 문자열 만 될 수 있습니다.
JSON 직렬화시 Map<FormIdentification, BaseForm>
키는 FormIdentification
. GSON이 할 수있는 최선의 방법 FormIdentification.toString()
은 키의 문자열을 가져 오는 데 사용 하는 것입니다.
그러나 JSON 역 직렬화 중에는 FormIdentification
문자열에서 가져 오는 방법을 알 수있는 방법이 없습니다 .
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다