【问题标题】:Android Java Spring JSON response has $ in key. How to parse?Android Java Spring JSON 响应有 $ 键。如何解析?
【发布时间】:2015-11-01 13:55:50
【问题描述】:

我是 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;
    }
}

任何帮助将不胜感激。

【问题讨论】:

  • 我怀疑 $ 是否有问题。
  • @Garry 在 Android Studio 中使用 $ in 变量会给我各种错误。此外,Java 似乎不鼓励在其文档中的变量中使用 $ 符号。

标签: java android json spring


【解决方案1】:

您可以使用MongoId 中的@JsonProperty("$id") 注解来说明 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;
    }
}

这是一个quick overview 供参考。

【讨论】:

  • 这非常有效。额外的问题:我可以以此为目标更深层次的价值吗?喜欢@JsonProperty("session/token")?
  • 我不确定这是否可以通过简单的注释来实现。您可能必须使用自定义反序列化器。例如,请参阅baeldung.com/jackson-deserialization
猜你喜欢
  • 2015-10-10
  • 1970-01-01
  • 2013-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-27
  • 1970-01-01
相关资源
最近更新 更多