1

Simple question/problem for anybody familiar with building APIs... I have many objects that I prefer to represent as a string rather than a Json object, for simplicity purposes.

For example, I have a date range which I could (and used to) place into an object (with start end end date members), but considering we can have multiple of these ranges, I could instead have this...

['20130210-20130315','20130520-20130524']

Which IMO looks a lot simpler and cleaner than

[
  {
    "start":"2013-02-10",
    "end":"2013-03-15"
   },
  {
    "start":"2013-05-20",
    "end":"2013-05-24"
  }
]

And this holds for various other objects which are in the main Json object for the service.

My dilemma of just treating them as Strings is that then I lose the ability to mark them with interfaces, which are used all throughout the code. (For instance, this Json in particular might be marked with a "Filter" interface which many methods take in.)

That said, is there any way to satisfy both of these conditions, i.e. having a custom Json object (implementing my own interfaces, etc.) AND have Jackson parse it like a String primitive? I'm hoping this can be accomplished without much work involving custom serialization & deserialization, since I have lots of objects.

Ryan
  • 729
  • 1
  • 10
  • 25
  • Oops, I duplicated [this](http://stackoverflow.com/questions/14180922/jackson-treat-object-as-primitive)... @JsonValue solves the problem. Coolio. – Ryan Mar 07 '14 at 23:09

1 Answers1

0

Hate duplicating posts, so in an attempt to add some value here -- this does exactly what I want with arrays --

public class MyAwesomeJson extends JacksonObject implements S {

   private final String value;

   public MyAwesomeJson(String value) {
     this.value = value;
   }

   @JsonValue
   public String getValue() {
     return value;
   }
}

Then to get the array form --

public class MyAwesomeJsonArray extends JacksonObject implements A {

   private final Set<MyAwesomeJson> values = Sets.newLinkedHashSet();

   public MyAwesomeJsonArray(MyAwesomeJson... values) {
     this.values.addAll(Arrays.asList(values));
   }

   @JsonValue
   public Set<MyAwesomeJson> getValues() {
     return values;
   }
}

System.out.println(new MyAwesomeJsonArray(new MyAwesomeJson("Yellow"), new MyAwesomeJson("Goodbye")));

["Yellow","Goodbye"]

Community
  • 1
  • 1
Ryan
  • 729
  • 1
  • 10
  • 25