簡體   English   中英

Android Java Spring JSON響應具有$ in鍵。 怎么解析?

[英]Android Java Spring JSON response has $ in key. How to parse?

我是Java新手。 我正在使用Spring來使用輸出JSON的REST API。 通過Spring網站上的教程,我可以輕松地將JSON響應轉換為所需類的對象。 現在的問題是,JSON響應中的鍵之一是$id 我不能用美元符號制作變量。 我假設我應該在某個位置定義一些配置,以便將這樣的名稱轉換為可接受的名稱。 我不知道

我的休息請求代碼:

protected LoginResult doInBackground(Void... params) {
    try {
        Log.i(TAG, "Making Login request");
        //TODO: Make this a setting
        final String url = "https://someurl.com/api/login";

        LoginCredentials login = new LoginCredentials("foo@bar.com", "qwerty123");

        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

        LoginResult result = restTemplate.postForObject(url, login, LoginResult.class);

        Log.d(TAG, "Got the LoginResult.");
        return result;
    } catch (Exception e) {
        //TODO: Exception handling
        Log.e(TAG, e.getMessage(), e);
    }

    return null;
}

生成的JSON看起來像這樣:

{
   "_id":{
      "$id":"98765432"
   },
   "name":"Person Guy",
   "email":"foo@bar.com",
   "roles":[
      "user"
   ],
   "active":true,
   "created":{
      "sec":1439117849,
      "usec":856000
   },
   "session":{
      "token":"12345678",
      "user_id":"98765432",
      "created":{
         "sec":1439134272,
         "usec":0
      },
      "last_extended":{
         "sec":1439134272,
         "usec":0
      },
      "expires":{
         "sec":1439998272,
         "usec":0
      }
   }
}

$id是困難的地方。 LoginResult類如下所示:

@JsonIgnoreProperties(ignoreUnknown = true)
public class LoginResult {
    private String name;
    private String email;
    private MongoId _id;
    /* Getters and setters */
}

MongoId類看起來像這樣(現在添加了JsonIgnoreProperties以避免出現異常):

@JsonIgnoreProperties(ignoreUnknown = true)
public class MongoId {
    private String id; //This is $id in the JSON response.

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

任何幫助將不勝感激。

您可以使用@JsonProperty("$id")在注釋MongoId告訴JSON是如何映射到Java對象:

@JsonIgnoreProperties(ignoreUnknown = true)
public class MongoId {
    @JsonProperty("$id") 
    private String id; //This is $id in the JSON response.

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

這是一個快速概述,以供參考。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM