将java.util.ArrayList [String]转换为json数组字符串

时间:2016-01-15 17:00:15

标签: scala json4s

我尝试使用json4s库(https://github.com/json4s/json4s)将String of String转换为json数组List:

 @ManagedBean
 @ApplicationScoped
 public class BookBean {

String name;
String description;
int categoryId;
Category category;

@Inject
public BookEJB bookEJB;

public void addBook(){

    Book book = new Book();
    book.setName(name);
    book.setDescription(description);
    book.setCategory(category);

    bookEJB.addBook(book);
}

public List<Book> getAllBooks(){
    return bookEJB.getAll();
}


public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public int getCategoryId() {
    return categoryId;
}

public void setCategoryId(int categoryId) {
    this.categoryId = categoryId;
}

public Category getCategory() {
    return category;
}

public void setCategory(Category category) {
    this.category = category;
}

public BookEJB getBookEJB() {
    return bookEJB;
}

public void setBookEJB(BookEJB bookEJB) {
    this.bookEJB = bookEJB;
}

导致错误:

object Convert { import scala.collection.JavaConversions._ import org.json4s._ import org.json4s.native.JsonMethods._ val l = new java.util.ArrayList[String]() l.add("1") l.add("1") l.add("1") println(compact(render(l.toList))) } 导致编译错误:

l.toList

是否需要将数组的每个元素转换为JValue?是否有将scala List [String]转换为json数组的标准方法?

1 个答案:

答案 0 :(得分:1)

Json4s要求org.json4s.Formats的实例在范围内,以便将Scala类型(如case类和本机集合)转换(序列化)为JSON。

以下是我对您拥有的转换器代码的看法:

object Convert {
  import scala.collection.JavaConverters._ // I prefer this to JavaConversions
  import org.json4s._
  import org.json4s.native.Serialization._ // provides write()

  implicit val formats = org.json4s.DefaultFormats 

  val l = new java.util.ArrayList[String]()
  l.add("1")
  l.add("1")
  l.add("1")

  val asJsonString = write(l.asScala)
  println(compact(parse(asJsonString)))
}

注意:

  • 我更喜欢JavaConverters和JavaConversions。它为集合提供了一个隐式定义的asScala方法,使其在代码中更加透明,发生了Java2Scala转换
  • 鉴于杰克逊的受欢迎程度和广泛的测试,我还建议使用杰克逊而不是原住民