I am encountering a problem in serializing an array of objects to json file. Please let me know where I'm making the mistake.
Object to be serialized :
package components;
public class UserGameInfo {
private int level;
private boolean isLocked;
public UserGameInfo() {
}
public UserGameInfo(final int level, final boolean isLocked) {
this.level = level;
this.isLocked = isLocked;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public boolean isLocked() {
return isLocked;
}
public void setLocked(boolean isLocked) {
this.isLocked = isLocked;
}
}
Object definitions:
public class LevelsInfoFileReader {
private Json fileJson;
private Logger logger;
private Array<LevelObjects> levelObjectsList;
private Array<UserGameInfo> userGameObjectsList;
....
}
Code for serializing the object :
//write to the file
try {
FileHandle newFile = Gdx.files.local(userInfoFilePath);
fileJson.toJson(userGameObjectsList, Array.class, UserGameInfo.class, newFile);
System.out.println(fileJson.prettyPrint(userGameObjectsList));
} catch (final Exception e) {
logger.error("Could not save user data to the filepath", e);
}
1st approach :
File contents after serialization : [{level:1},{level:2},{level:3,isLocked:true},{level:4,isLocked:true},{level:5,isLocked:true},{level:6,isLocked:true},{level:7,isLocked:true},{level:8,isLocked:true},{level:9,isLocked:true},{level:10,isLocked:true}]
The problem here is that, though no class information is displayed, the boolean variable is not shown for level1 and level2 in the serialized json file. However, I put a debug point and checked the array object before serialization. It does contain the list properly as shown int the attached snapshot
2nd approach
The second approach I tried was with pretty print. However, the class information of the array elements is also displayed in the .json file :
Following is the .json file content :
[
{
class: components.UserGameInfo
level: 1
}
{
class: components.UserGameInfo
level: 2
}
{
class: components.UserGameInfo
level: 3
isLocked: true
}
]
My final expected output is :
[
{
"level": 1,
isLocked : false
}
{
"level": 2.
isLocked : false
}
{
"level": 3,
isLocked: true
}
]