簡體   English   中英

將java類數據轉換為JSON格式?

[英]Convert the java class data into JSON format?

我正在使用spring進行Java項目。所以我使用Jackson庫轉換為獲取JSON格式。

我的java類將是,

public class ChatInteraction extends Interaction{

    private int ticketId;
    private String name;

    private String interactionType ;
    private LinkedList<InteractionInfo> interactions;

    public ChatInteraction(Message response) {
        super(response);
        interactions = new LinkedList<InteractionInfo>();
    }


    public int getTicketId() {
        return ticketId;
    }

    public void setTicketId(int ticketId) {
        this.ticketId = ticketId;
        System.out.println("Ticket Id for Interaction : "+this.ticketId);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
        System.out.println("Name for Interaction : "+this.name);
    }


    public LinkedList<InteractionInfo> getInteractions() {
        return interactions;
    }

    public String getInteractionType() {
        return interactionType;
    }

    public void setInteractionType(String interactionType) {
        this.interactionType = interactionType;
    }


    public void addInteraction(InteractionInfo interaction) {
        this.interactions.add(interaction);
    }


    public void accept(int proxyId,String intxnId,int ticketId){

        RequestAccept reqAccept = RequestAccept.create();
        reqAccept.setProxyClientId(proxyId);
        reqAccept.setInteractionId(intxnId);
        reqAccept.setTicketId(ticketId);

        System.out.println("New Chat RequestAccept Request Object ::: "+reqAccept.toString());

        try{
            if(intxnProtocol.getState() == ChannelState.Opened){

                Message response = intxnProtocol.request(reqAccept);

                System.out.println("New Chat RequestAccept Response ::: "+response.toString());

                if(response != null ){

                    if( response.messageId() == EventAck.ID){
                        System.out.println("Accept new chat  success !");
                        //EventAccepted accept = (EventAccepted)response;
                        //return "New chat Interaction accepted";
                    }else if(response.messageId() == EventError.ID){
                        System.out.println("Accept new chat Failed !");
                        //return "New chat Interaction rejected";
                    }
                }

            }else{
                System.out.println("RequestAccept failure due to Interaction protocol error  !"); 
            }


        }catch(Exception acceptExcpetion){
            acceptExcpetion.printStackTrace();
        }

    }


    public void join(String sessionId, String subject) {

        RequestJoin join = RequestJoin.create();
        join.setMessageText(MessageText.create(""));
        join.setQueueKey("Resources:"); //Add the chat-inbound-key in multimedia of the optional tab values of the softphone application in CME
        join.setSessionId(sessionId);
        join.setVisibility(Visibility.All);
        join.setSubject(subject);
        KeyValueCollection kvc = new KeyValueCollection();
        join.setUserData(kvc);

        System.out.println("Join Request Object ::: "+join.toString());

        try {

            if(basicProtocol != null && basicProtocol.getState() == ChannelState.Opened){
                Message response = basicProtocol.request(join);

                if(response != null){

                    System.out.println("RequestJoin response ::: "+response);

                    if (response.messageId() == EventSessionInfo.ID) {
                        System.out.println("Join Request success !");
                    }else{
                        System.out.println("Join Request Failed !");
                    }
                }
            }else{
                System.out.println("BasicChat protocol Error !");
                //return "BasicChat protocol Error !";
            }
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }

    }


}

我需要只有interactionTypeinteractions這一的屬性JSON格式一樣,

 {"interactionType":"invite","interactions" : [{"xx":"XX","yy":"YY"},{"xx":"XX","yy":"YY"}]} 

注意 :

  1. 我不需要這個類的其他屬性。

  2. 此外, 交互屬性沒有SETTER 而不是我有addInteractions()方法。 這會影響JSON轉換的任何行為嗎?

  3. 我還有其他一些方法,比如accept(...)Join(...)

  4. 我正在使用jackson-all-1.9.0.jar

您可以使用@JsonIgnore注釋不需要的字段 - 請參閱傑克遜的注釋手冊 使用您的代碼就是這樣:

public class ChatInteraction extends Interaction{
    @JsonIgnore
    private int ticketId;
    @JsonIgnore
    private String name;

    private String interactionType ;
    private LinkedList<InteractionInfo> interactions;

您可以使用可在類級別使用的@JsonIgnoreProperties批注實現此@JsonIgnoreProperties

來自JavaDoc

可用於抑制屬性序列化(在序列化期間)或忽略處理讀取的JSON屬性的注釋(在反序列化期間)。

例:

 // to prevent specified fields from being serialized or deserialized
 // (i.e. not include in JSON output; or being set even if they were included)
 \@JsonIgnoreProperties({ "internalId", "secretKey" })

示例,在您的情況下:

@JsonIgnoreProperties({ "ticketId", "name" })
public class ChatInteraction extends Interaction{
    ....
}

最后,我通過別人的答案在線程和計算器類似的回答得到了解決

  1. 我標志着@JsonIgnore在子類和超類的FVU建議在無用場

  2. 我使用了myObjectMapper.setVisibility(JsonMethod.FIELD, Visibility.ANY); 在我的objectMapper中建議在其他線程中,

     ObjectMapper mapp = new ObjectMapper(); mapp.setVisibility(JsonMethod.FIELD, Visibility.ANY); try { json = mapp.writeValueAsString(info); info.clear(); System.out.println("Chat Info in JSON String is :::> "+json); } catch (Exception e) { e.printStackTrace(); } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM