Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

java - ObjectMapper ignores some fileds when mapping to JSON

So my issue is that when mapping a class to JSON, it won't map all the fields the class has

Card:

public class Card {
    private String name;
    private String description;
    private StatusCard status;
    private List<String> CardHistory;
    public enum StatusCard{TODO, INPROGRESS, TOBEREVISED, DONE};

    public Card(String name, String desc){
        this.name = name;
        description = desc;
        status = StatusCard.TODO;
        CardHistory = new ArrayList<>();
    }

    public Card(){}

    // getters and setters
}

This class is used within another class, in an ArrayList<Card> cardList, but when I map this class to JSON, this is the only fields it maps

JSON:

... "cardList":[{"name":"test","status":"TODO"}] ...

and I can't figure out why. This is the method that adds a new card by the server:

public String addCard(String projectName, String cardName, String desc, String nickUtente) {
    if (projects.isEmpty())
        return "No projects are currently present";
    if (projectName.isEmpty() || cardName.isEmpty() || desc.isEmpty() || nickUtente.isEmpty())
        return "Missing one or more arguments";

    for (Project p : projects) {
        if (p.getName().equalsIgnoreCase(projectName)){
            if (!p.isMember(nickUtente))
                return nickUtente + " does not belong to the project";
            String code = p.addCard(cardName, desc);
            if (code.equalsIgnoreCase("ok")) {
                try {
                    om.writeValue(projectFile,projects);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return code;
        }
    }
    return "Project " + projectName + " not found";
}

This is the Project class using classes from com.fasterxml.jackson if you need to know:

public class Project implements Serializable {

    private String name;
    private String nickUtente;
    private ArrayList<Card> cardList;
    private ArrayList<String> users;
    private ArrayList<String> TODO;
    private ArrayList<String> INPROGRESS;
    private ArrayList<String> TOBEREVISED;
    private ArrayList<String> DONE;
    private String MulticastAddress;
    private int port;

    /*
    @JsonIgnore
    private File projDir;
    @JsonIgnore
    private final ObjectMapper map;
    */

    public Project(String name, String nickUtente, String multiaddr, int port) {
        this.name = name;
        this.nickUtente = nickUtente;
        cardList = new ArrayList<>();
        users = new ArrayList<>();
        users.add(nickUtente);
        TODO = new ArrayList<>();
        INPROGRESS = new ArrayList<>();
        TOBEREVISED = new ArrayList<>();
        DONE = new ArrayList<>();
        MulticastAddress = multiaddr;
        this.port = port;
        // map = new ObjectMapper();
        // map.enable(SerializationFeature.INDENT_OUTPUT);
        // projDir = new File("./BackupCards/" + name);
        // if(!projDir.exists()) projDir.mkdir();
    }

    public Project(){
        // this.map = new ObjectMapper();
        // map.enable(SerializationFeature.INDENT_OUTPUT);
    }
    
    // getters and setters

    public boolean isMember(String user){
        if(users.isEmpty())
            return false;
        for(String s : users) {
            if (user.equals(s))
                return true;
        }
        return false;
    }

    public String addMember(String s) {
        if (s.isEmpty()){
            System.out.println("Missing name");
            return "err";
        }
        if (users.contains(s)) {
            System.out.println("Member exists already");
            return "err";
        }
        users.add(s);
        return "ok";
    }

    public String addCard(String cardName, String desc){
        if(cardName.isEmpty() || desc.isEmpty())
            return "Missing name and/or description";
        Card c = new Card(cardName, desc);
        cardList.add(c);
        TODO.add(cardName);
        /* 
        File cardFile = new File(projDir + "/" + cardName + ".json");
        if (!cardFile.exists()) {
            try {
                cardFile.createNewFile();
            } catch (IOException e) { e.printStackTrace(); }
        }
        //Backup card file
        try {
            map.writeValue(cardFile, c);
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        return "ok";
    }

    public String moveCard(String cardName, String startingList, String destList){
        if(cardName.isEmpty() || startingList.isEmpty() || destList.isEmpty())
            return "Missing one or more arguments";
        for(Card c : cardList){
            if(c.getName().equalsIgnoreCase(cardName)){
                switch(destList){
                    case "TODO":
                        if(startingList.equals("TODO"))
                            return "Card is already in " + startingList;
                        return "Cannot move card back to TODO";
                    case "INPROGRESS":
                        if(startingList.equals("INPROGRESS"))
                            return "Card already is in INPROGRESS";
                        if(startingList.equals("DONE"))
                            return "Card is done. Cannot change status anymore";
                        if(TODO.contains(cardName)){
                            TODO.remove(cardName);
                            INPROGRESS.add(cardName);
                            c.setStatus("INPROGRESS");
                            c.getCardHistory().add(startingList);
                            //System.out.println("Card moved from TODO to INPROGRESS");
                            return "ok";
                        }
                        if(TOBEREVISED.contains(cardName)){
                            TOBEREVISED.remove(cardName);
                            INPROGRESS.add(cardName);
                            c.setStatus("INPROGRESS");
                            c.getCardHistory().add(startingList);
                            //System.out.println("Card moved from TOBEREVISED to INPROGRESS");
                            return "ok";
                        }
                        return "Card not found";
                    case "TOBEREVISED":
                        if(!startingList.equals("INPROGRESS"))
                            return "Can only move to TOBEREVISED from INPROGRESS";
                        if(INPROGRESS.contains(cardName)){
                            INPROGRESS.remove(cardName);
                            TOBEREVISED.add(cardName);
                            c.setStatus("TOBEREVISED");
                            c.getCardHistory().add(startingList);
                            //System.out.println("Card moved FROM INPROGRESS TO TOBEREVISED");
                            return "ok";
                        }
                    case "DONE":
                        if(startingList.equals("TODO"))
                            return "Cannot move card to DONE from TODO";
                        if(INPROGRESS.contains(cardName)){
                            INPROGRESS.remove(cardName);
                            DONE.add(cardName);
                            c.getCardHistory().add(startingList);
                            c.setStatus("DONE");
                            //System.out.println("Moved card from INPROGRESS to DONE");
                            return "ok";
                        }
                        if(TOBEREVISED.contains(cardName)){
                        TOBEREVISED.remove(cardName);
                        DONE.add(cardName);
                        c.setStatus("DONE");
                        c.getCardHistory().add(startingList);
                        //System.out.println("Moved card from TOBEREVISED to DONE");
                        return "ok";
                        }
                        return "Card not found";
                    }
                }
            }
        return "Card not found";
    }

    public void showMembers() {
        if (users.isEmpty())
            System.out.println("No user belongs to this project");
        for (String s : users)
            System.out.println(s);
    }

    public void showCards() {
        if (TODO.isEmpty() && INPROGRESS.isEmpty() && TOBEREVISED.isEmpty() && DONE.isEmpty())
            System.out.println("No cards to be shown");
        if (TODO.isEmpty()) {
            System.out.println("No cards TODO");
        } else {
            System.out.println("Cards TODO:");
            for (String s : TODO)
                System.out.println(s);
        }
        if (INPROGRESS.isEmpty()) {
            System.out.println("No cards IN PROGRESS");
        } else {
            System.out.println("Cards INPROGRESS:");
            for (String s : INPROGRESS)
                System.out.println(s);
        }
        if (TOBEREVISED.isEmpty())
            System.out.println("No cards TOBEREVISED");
        else {
            System.out.println("Cards TOBEREVISED:");
            for (String s : TOBEREVISED)
                System.out.println(s);
        }
        if (DONE.isEmpty())
            System.out.println("No cards DONE");
        else {
            System.out.println("Cards DONE:");
            for (String s : DONE)
                System.out.println(s);
        }
    }

    public Card getCard(String name) {
        if (cardList.isEmpty())
            return null;
        for (Card c : cardList){
            if (c.getName().equalsIgnoreCase(name))
                return c;
        }
        return null;
    }

    public List<UserStatusInfo> getCardList() {
        if(cardList.isEmpty())
            return null;
        List<UserStatusInfo> list = new ArrayList<>();
        for(Card c : cardList)
            list.add(new UserStatusInfo(c.getName(),c.getStatus()));
        return list;
    }

  /*  public void delProjDir(){
        try {
            Files.walk(projDir.toPath()).sorted(Comparator.reverseOrder()).map(Path::toFile)
                    .forEach(File::delete);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
*/
}


question from:https://stackoverflow.com/questions/65934324/objectmapper-ignores-some-fileds-when-mapping-to-json

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is here

public List<UserStatusInfo> getCardList() {
    if(cardList.isEmpty())
        return null;
    List<UserStatusInfo> list = new ArrayList<>();
    for(Card c : cardList)
        list.add(new UserStatusInfo(c.getName(),c.getStatus()));
    return list;
}

You have private property ArrayList<Card> cardList and public method List<UserStatusInfo> getCardList(). Since ObjectMapper follows JavaBean conventions during serialization it only accesses public properties and public getter methods, so when cardList is mapped into JSON, not cardList property is actually serialized, but result of getCardList() method invocation hence not Card instances are serialized but UserStatusInfo instances (that seem to have only name and status).

You have to create ArrayList<Card> getCardList() method that returns cardList property, and rename current List<UserStatusInfo> getCardList() to something else

OR

Extend UserStatusInfo class so that it has all corresponding properties from Card


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...