开发者

Converting from json to a class with gson does not appear to do anything

开发者 https://www.devze.com 2023-02-14 10:36 出处:网络
I am attempting to deserialize a json string using gson. Here is my code static class ReturnPramaters {

I am attempting to deserialize a json string using gson. Here is my code

static class ReturnPramaters {
    public ReturnPramaters()
    {
    }
    public Boolean LoginFailed = true;
    public String LoginFailedReason = "";
    public String AppPath  = "";
    public String WorkstiaonGuid = "";
    public String RDPUsername  = "";
    public String RDPPassword  = "";
    public int StartMode = -1;
    public String ServerAddress  = "";
}
public static void main(String[] args) {
    String json = sendGetRequest开发者_如何学C("http://example.com:80/Rdp/json/login","username=test&password=1234");
    Gson gson = new Gson();
    ReturnPramaters para = gson.fromJson(json, ReturnPramaters.class);
    if(para.LoginFailed)
        JOptionPane.showMessageDialog(null, para.LoginFailedReason, "Login Failed",JOptionPane.ERROR_MESSAGE);
    else {
        //...
    }
}

here is my json string that is retured from the get request.

"{"d":{"__type":"ReturnPramaters:#ServerApp","AppPath":"C:\\Remote Desktop Manager\\Launcher\\Launcher.exe","LoginFailed":false,"LoginFailedReason":null,"RDPPassword":"XjE2QAL","RDPUsername":"test09","ServerAddress":"example.com","StartMode":1,"WorkstiaonGuid":"96175701-f72a-44e9-8ee1-6eb756293654"}}"

However after ReturnPramaters para = gson.fromJson(json, ReturnPramaters.class); para still has all of it's uninitialized values. What is going wrong that is causing this to fail?


It seems that JSON you are mapping to is wrapped in another object with d and _type fields.

So create a simple wrapper Class:

class JsonWrapper{
    public ReturnPramaters d;
}


try truncating the incoming string before passing to GSON, so that it looks like this

"{
    "AppPath":"C:\\Remote Desktop Manager\\Launcher\\Launcher.exe",
    "LoginFailed":false,
    "LoginFailedReason":null,
    "RDPPassword":"XjE2QAL",
    "RDPUsername":"test09",
    "ServerAddress":"example.com",
    "StartMode":1,
    "WorkstiaonGuid":"96175701-f72a-44e9-8ee1-6eb756293654"
}"

The object that you currently have in JSON represents the following Java object

public class MyClass{
  ReturnPramaters d;
}


Your type class is static. Is that going to work?

0

精彩评论

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