bluelinelabs / LoganSquare

Screaming fast JSON parsing and serialization library for Android.
Apache License 2.0
3.21k stars 306 forks source link

[Feature Suggestion]: Path expression for fields. #44

Open curioustechizen opened 9 years ago

curioustechizen commented 9 years ago

It would be great to be able to annotate a field with an XPath-like expression in addition to just a field name. The use case for this is to have a flatter POJO hierarchy than the JSON.

Example:

{
  "some-meta-data": "foobar",
  "comment": 
    {
      "user": "Me",
      "timestamp": 12345678,
      "text": "WooHoo what an awesome comment"
    }
}

Currently, if I am not interested in the metadata, I am still forced to create a top level Java object.

class Response {

  @JsonField
  Comment comment;

  static class Comment {
    @JsonField String user;
    @JsonField long timestamp;
    @JsonField String text;
  }
}

Using an XPath-like expression, I could maybe even eliminate the need to create the top-level Response class altogether.

@JsonPathRoot("$.comment")
class Comment {
  @JsonField String user;
  @JsonField long timestamp;
  @JsonField String text;
}

Or perhaps, using a XPath expression, that might be @JsonPathRoot("//comment").

Prior art:

IMO these libraries serve a different purpose - querying large JSON data to extract certain information. For POJO-JSON mapping, a far simpler syntax would suffice.

None of the popular JSON mapping libraries for Java support this currently. GSON does provide a way to parse a JsonPath expression, but I did not find a way to specify the Path in place of a field name as an annotation.

yongjhih commented 9 years ago

:+1:

ppamorim commented 8 years ago
jasonni commented 7 years ago

👍

curioustechizen commented 7 years ago

There is now a library to do this for GSON. It is actually an annotation processor - https://github.com/LachlanMcKee/gsonpath