简体   繁体   English

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

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

I am doing the Java project with spring .So I am using the Jackson library to convert to get the JSON format. 我正在使用spring进行Java项目。所以我使用Jackson库转换为获取JSON格式。

My java Class will be , 我的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();
        }

    }


}

I need to get only the interactionType and interactions property of this class in the JSON format like , 我需要只有interactionTypeinteractions这一的属性JSON格式一样,

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

Note : 注意 :

  1. I don't need the other properties of this class. 我不需要这个类的其他属性。

  2. Also there is no SETTER for the interactions property . 此外, 交互属性没有SETTER Instead of that I have the addInteractions() method . 而不是我有addInteractions()方法。 Does this affects any behaviour of JSON conversion ? 这会影响JSON转换的任何行为吗?

  3. Also I have some other methods like accept(...) , Join(...) . 我还有其他一些方法,比如accept(...)Join(...)

  4. I am using the jackson-all-1.9.0.jar 我正在使用jackson-all-1.9.0.jar

You can annotate the unneeded fields with @JsonIgnore - see Jackson's manual on annotations . 您可以使用@JsonIgnore注释不需要的字段 - 请参阅杰克逊的注释手册 That's what it will look like, using your code: 使用您的代码就是这样:

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

    private String interactionType ;
    private LinkedList<InteractionInfo> interactions;

You can use achieve this by using the @JsonIgnoreProperties annotation that can be used on class level . 您可以使用可在类级别使用的@JsonIgnoreProperties批注实现此@JsonIgnoreProperties

From JavaDoc : 来自JavaDoc

Annotation that can be used to either suppress serialization of properties (during serialization), or ignore processing of JSON properties read (during deserialization). 可用于抑制属性序列化(在序列化期间)或忽略处理读取的JSON属性的注释(在反序列化期间)。

Example: 例:

 // 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" })

Example, In your case: 示例,在您的情况下:

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

Finally I got the solution by others answers in the thread and similar answers in stackoverflow, 最后,我通过别人的答案在线程和计算器类似的回答得到了解决

  1. I marked the @JsonIgnore in the unwanted field in the sub class and super class suggested by fvu . 我标志着@JsonIgnore在子类和超类的FVU建议在无用场

  2. I have used the myObjectMapper.setVisibility(JsonMethod.FIELD, Visibility.ANY); 我使用了myObjectMapper.setVisibility(JsonMethod.FIELD, Visibility.ANY); in my objectMapper suggested in other thread like, 在我的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.

相关问题 将json格式的数据转换/解析为Android中的Java - Convert/parse data in json format to java in Android 如何将 Json 字符串/数据转换为 Java Class? - How to convert a Json String/Data to a Java Class? 我要转换java object中的json格式数据ZD52387880E1EA228171972D3759Z1 - I want to convert json format data in java object in Java transformation 如何使用Java将动态Json转换为POJO类的特定格式 - How to convert dynamic Json to specific format of POJO class using Java 如何在不创建 ZA8CFDE6331BD59EB2ACZ6F8911C4B666 的情况下将 java class 转换为 json 格式结构 - How to convert java class to json format structure without creating object 将Apache Camel JSON数据格式从XML转换为Java DSL - Convert Apache Camel JSON data format from XML to Java DSL 使用GSON将JSON数据转换为Java对象(包括Object类) - Convert JSON data to Java object (including the Object class) using GSON java中的基本数据格式转换 - Basic data format convert in java 在Java中将JSON从一种格式转换为另一种JSON格式 - Convert JSON from one format to another JSON format in java 将java.util.Date转换为json格式 - Convert java.util.Date to json format
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM