16

I'm using JAXB/Jersey (1.3) to convert java to json in a REST API. The java class I'm returning is like:

public class MyClass {  
  List<String> myTags;
  public List<String> getMyTags() {
    return myTags;
  }
}

My problem is that if there is only a single element in the list myTags, then the data is converted to json as a string object, not an array of strings. That is, I get:

{
  "myTags": "myString"
}

What I want is:

{
   "myTags": ["myString"]
}

Anyone know whats up ?

Kevin
  • 11,521
  • 22
  • 81
  • 103
  • Which library are you using for converting JAXB annotated classes to JSON? – Luciano Fiandesio Apr 12 '11 at 20:50
  • Sun JAXB Reference Implementation, v2.1.12 – Kevin Apr 12 '11 at 21:03
  • Yeah, but which library do you use to convert the class to JSON? JAXB converts classes to XML, you need another library to convert to JSON, such as Jettison or Jackson – Luciano Fiandesio Apr 12 '11 at 21:05
  • I'm using Maven, and only specifying the jersey dependencies, so I'm not explicitly specifying a library. However, looking at the resulting WAR file created, I'm assuming that Jersey is pulling in Jackson as a dependency (v1.7.1). – Kevin Apr 12 '11 at 21:16
  • Yep, its Jackson :- the dependencies are listed in here: http://download.java.net/maven/2/com/sun/jersey/jersey-json/1.6/jersey-json-1.6.pom – Kevin Apr 12 '11 at 21:17
  • 2
    The link you have provided also has a dependency to Jettison, that has the problem you mentioned ( single element array rendered as non-array in Json). Can this help: http://jersey.576304.n2.nabble.com/Single-Element-Arrays-and-JSON-td5532105.html – Luciano Fiandesio Apr 12 '11 at 21:22

2 Answers2

7

As per Luciano's comments, the problem lies in the fact that Jersey wasn't using Jackson as the default JSON converter. I tried excluding Jettison from the pom dependency, but it still didn't resolve the issue. I found an answer to explicitly tell Jersey to use Jackson here:

How can I customize serialization of a list of JAXB objects to JSON?

Community
  • 1
  • 1
Kevin
  • 11,521
  • 22
  • 81
  • 103
-1

I was facing the similar issue and found simple fix. Marking @JsonSerialize instead of @XmlRootElement has worked for me.

@JsonSerialize
public class MyClass {  
  List<String> myTags;
  public List<String> getMyTags() {
    return myTags;
  }
}
Manju
  • 39
  • 3