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

I’m new to Java. I’m using Spring to consume a REST api that outputs JSON. With the tutorials on the Spring website I can easily have the JSON response converted to an object of my desired class. The problem is now that one of the keys in the JSON response is $id. I cannot make a variable with a dollar sign in it. I assume I should define some configuration somewhere that such a name would be converted into something acceptable. I don’t know how.

My Rest request code:

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("[email protected]", "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;
}

The resulting JSON looks something like this:

{
   "_id":{
      "$id":"98765432"
   },
   "name":"Person Guy",
   "email":"[email protected]",
   "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
      }
   }
}

The $id part is where things get difficult. The LoginResult class looks like this:

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

The MongoId class looks like this (The JsonIgnoreProperties is now added to avoid exceptions):

@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;
    }
}

Any help would be largely appreciated.

Answer

You can use the @JsonProperty("$id") annotation in MongoId to tell how the JSON is mapped to your Java object:

@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;
    }
}

Here is a quick overview for reference.

Leave a Reply

Your email address will not be published. Required fields are marked *