我尝试使用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数组的标准方法?
答案 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)))
}
注意:
asScala
方法,使其在代码中更加透明,发生了Java2Scala转换