从json转换为带有gson的类似乎没有做任何事情

时间:2011-02-28 17:30:25

标签: java gson json

我正在尝试使用gson反序列化json字符串。这是我的代码

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("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 {
        //...
    }
}

这是我的json字符串,它是从get请求中退出的。

"{"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"}}"

然而,在ReturnPramaters para = gson.fromJson(json, ReturnPramaters.class); para之后仍然具有所有未初始化的值。导致此失败的问题是什么?

3 个答案:

答案 0 :(得分:3)

您要映射到的JSON似乎包含在另一个包含d_type字段的对象中。

所以创建一个简单的包装类:

class JsonWrapper{
    public ReturnPramaters d;
}

答案 1 :(得分:1)

尝试在传递给GSON之前截断传入的字符串,使其看起来像这样

"{
    "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"
}"

您当前在JSON中拥有的对象表示以下Java对象

public class MyClass{
  ReturnPramaters d;
}

答案 2 :(得分:0)

您的类型类是静态的。这会起作用吗?