当前位置: 首页 > 知识库问答 >
问题:

如何利用Spring的RestController将JSON反序列化为模型对象

郜昊苍
2023-03-14

我正在使用Betfair的API开发一个REST web应用程序,因此我需要序列化/反序列化JSON,以便发送HttpRequest并读取HttpResponse。

@EnableWebMvc
@RestController
public class LoginController {
    private final String APP_KEY = "myAppKey";
    private final String LOGIN_END_POINT = "https://identitysso.betfair.it/api/login";
    private final String LOGOUT_END_POINT = "https://identitysso.betfair.it/api/logout";
    private final String ACCOUNT_END_POINT = "https://api.betfair.com/exchange/account/json-rpc/v1";
    private String token;

    @RequestMapping(value = "/index", method = RequestMethod.POST, params = { "firstName", "lastName" })
    public ModelAndView getAccountDetails(User user, @RequestBody AccountDetailsResponse accountDetails) {
        String response = null;

        JsonRequest jsonRequest = new JsonRequest();
        jsonRequest.setJsonrpc("2.0");
        jsonRequest.setMethod("AccountAPING/v1.0/getAccountDetails");
        jsonRequest.setId("1");

        response = HttpRequestHandler.sendRequest("POST", ACCOUNT_END_POINT, APP_KEY, jsonRequest);

        if(response.equals("ERROR")) {
            String message = "Error";
            return new ModelAndView("home", "message", message);
        }

        else {
            user.setFirstName(accountDetails.getResult().getFirstName());
            user.setLastName(accountDetails.getResult().getLastName());

            return new ModelAndView("home", "user", user);
        }
    }
}
public static String sendPostRequest(String url, String APP_KEY, JsonRequest jsonRequest) {
    try {
        URL urlRequest = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) urlRequest.openConnection();

        connection.setRequestMethod("POST");
        connection.addRequestProperty("Accept", "application/json");
        connection.addRequestProperty("X-Application", APP_KEY);

        int responseCode = connection.getResponseCode();

        if(responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }

            in.close();

            if(response.toString().contains("error")) {
                return "ERROR";
            }
            else
                return response.toString();
        }
        else
            return "ERROR";

    } 
    catch (MalformedURLException e) {
        return "ERROR";
    } 
    catch (IOException e) {
        return "ERROR";
    }
}
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>RestController test</title>
</head>
<body>

<span th:if = "${user.logged}">
Welcome, <span th:text = "${user.firstName}"></span> <span th:text = "${user.lastName}"></span>
</span>

<p><span th:text = "${message}"></span></p>

</body>
</html>
public class User {
    private Long id;
    private String firstName;
    private String lastName;
    private String email;
    private String password;
    private Double toBetBalance;
    private boolean logged;

    public User() { }

    //getters and setters
}
public class AccountDetailsResponse {
    private String jsonrpc;
    private Result result;
    private String id;

    public AccountDetailsResponse() { }

    //getters and setters
}
public class Result {
    private String currencyCode;
    private String firstName;
    private String lastName;
    private String localeCode;
    private String region;
    private String timezone;
    private Float discountRate;
    private Integer pointsBalance;
    private String countryCode;

    public Result() { }

    //getters and setters
}
[  
   {  
      "jsonrpc":"2.0",
      "result":{  
         "currencyCode":"EUR",
         "firstName":"My name",
         "lastName":"My lastname",
         "localeCode":"it_IT",
         "region":"GBR",
         "timezone":"CET",
         "discountRate":0.0,
         "pointsBalance":0,
         "countryCode":"IT"
      },
      "id":1
   }
]

POM依赖项

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-framework-bom</artifactId>
            <version>4.2.5.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
    </dependency>

    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf</artifactId>
        <version>2.1.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring4</artifactId>
        <version>2.1.4.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.2</version>
    </dependency>

</dependencies>

我错在哪?

共有1个答案

周昊乾
2023-03-14

你不是应该

response.getResult().getFirstName(); 
response.getResult().getLastName();

在LoginController的else块中?

 类似资料:
  • 问题内容: 我的Spring MVC(v3.2.0.RELEASE)Web应用程序中具有以下对象模型: 将Order类序列化为JSON时,得到以下结果(正是我想要的结果): 不幸的是,如果我使用上述JSON并尝试将其反序列化回我的对象​​模型,则会收到以下异常: 无法读取JSON:无法在[来源:org.apache.catalina.connector.CoyoteInputStream@1962

  • 问题内容: 我在使用AJAX访问的Java服务器应用程序中有一个字符串。它看起来像以下内容: 当从服务器提取字符串时,是否有一种简单的方法可以将其转换为活动的JavaScript对象(或数组)?还是我必须手动拆分字符串并手动构建对象? 问题答案: 现代浏览器支持。 在不浏览器,您可以包括在库中。

  • 问题内容: 如何将上述字符串反序列化为java对象。 我正在使用的类是 问题答案: @基达 我假设您可以控制JSON输入字符串的创建方式。我认为JSON字符串格式不正确,无法对地图类型进行默认的GSON反序列化。 我已经修改了输入字符串供您考虑,这将导致非null的LocalLocationId 如果我对输入字符串的假设不正确,请发表评论。 编辑1:由于无法修改输入,请考虑编写自定义解串器。以下是

  • 有没有办法将一般对象序列化为Json并将Json反序列化为对象<如果对象是一个实体,我可以使用Jackson 2库来实现这个目的<但是如果对象是一个普通类,我该怎么做呢? 例如,我想序列化com.datastax.driver.core.querybuilder。将更新为Json并保存到DB,然后搜索并反序列化它以更新对象,最后将其用作com.datastax.driver.core.Sessio

  • 问题内容: 我的JSON有点弱,所以我需要一些帮助。 我正在尝试反序列化用户的JSON: 放入我用属性装饰的对象中: 我得到以下异常: Newtonsoft.Json.JsonSerializationException:在JSON中找不到必需的属性’user_id’。 这是因为JSON对象是一个数组吗?如果是这样,如何将其反序列化为一个User对象? 提前致谢! 问题答案: 正如Alexandr

  • 问题内容: 我需要将一些对象序列化为JSON并发送到WebService。如何使用org.json库?否则我将不得不使用另一个?这是我需要序列化的类: 我只放了类的变量和构造函数,但也有getter和setter方法。所以如果有人可以帮忙 问题答案: 没有注释的简单方法是使用Gson库 就那么简单: