开发者

JSON sending class A goes in class B

I am starting out on Restful web services and learning through JSON google gson. Though till now i have just made my server producer and json consumer application.

and i am loving it.

Now this is my consumer code: it has a TextMessages class object message

private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
InputStreamReader reader = null;
String name = nameTextfield.getText();
String url = "http://myurl/" + name;
    try {
        try {
            reader = new InputStreamReader(new URL(url).openStream());
        } catch (MalformedURLException ex) {
            Logger.getLogger(StartClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    } catch (IOException ex) {
            Logger.getLogger(StartClient.class.getName()).log(Level.SEVERE, null, ex);
    }

    TextMessages message = new Gson().fromJson(reader, TextMessages.class);

    JOptionPane.showMessageDialog(this, message.getMessage(), "Welcome" + message.sumAllIntegers(), 
JOptionPane.INFORMATION_MESSAGE);

}

// class TextMessages

package use;

开发者_StackOverflowpublic class TextMessages{
private String message;
private int a,b,c,d,wee;

public TextMessages(String __message){
    message = __message;        
}
public TextMessages(){
}

public String getMessage(){
    return message;
}

public void setMessage(String __message){
    message = __message;
}

}

Now server is sending JSON of class OtherTestMessage

public class TextMessage {
    private String message;
    //getter and setter functions
    // no int a,b
.....

Why is it working right ? Shoule it be working right ? is it again languages philosophy? how does JSON convert things. Or is it donot ? Just copying data ?


The gson library is looking at the JSON and mapping what it can to the class you provide.

Both of your classes have a String called message in them. gson is taking the message element in the JSON and storing the value in both cases. In your TextMessages class, it will also store the values for a, b, etc if those elements are present in the JSON.

In the case of your TextMessage class that only has String message, the additional elements in the JSON (a,b, etc) are silently ignored if they are present.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜