将java类数据转换为JSON格式?

时间:2013-09-18 15:52:25

标签: java json spring jackson

我正在使用 spring 进行 Java 项目。因此我使用Jackson库进行转换以获得JSON格式。< / p>

我的 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();
        }

    }


}

我只需要以 JSON 格式获取此interactionTypeinteractions属性,例如

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

注意:

  1. 我不需要此类的其他属性。

  2. 交互属性也没有 SETTER 。而不是我有 addInteractions()方法。这是否会影响 JSON 转换的任何行为?

  3. 此外,我还有其他一些方法,例如接受(...)加入(...)

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

3 个答案:

答案 0 :(得分:4)

您可以使用@JsonIgnore注释不需要的字段 - 请参阅杰克逊的manual on annotations。使用您的代码就是这样:

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

    private String interactionType ;
    private LinkedList<InteractionInfo> interactions;

答案 1 :(得分:3)

您可以使用可在班级上使用的@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{
    ....
}

答案 2 :(得分:2)

最后我得到了其他人在线程中的答案解决方案以及stackoverflow中的类似答案,

  1. 我在 fvu 建议的子类和超类中标记了不需要的字段中的@JsonIgnore

  2. 我在其他帖子中建议的 objectMapper 中使用了myObjectMapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);

    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();
    }