3
\$\begingroup\$

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 snapshotenter image description here 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
}
]
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$
  1. to remove class information, use fileJson.setTypeName(null)
  2. to display all infomation including default value (in your case "false" is default of boolean), use fileJson.setUsePrototypes(false);

see more in documents

\$\endgroup\$
1
  • \$\begingroup\$ Wow you're a lifesaver, I really needed to know that. \$\endgroup\$
    – Hasen
    Jul 9, 2021 at 10:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .