简体   繁体   English

Java JSON序列化器Play框架

[英]Java JSON serializer Play Framework

Hi I am using the Play Framework 2.3 and i want to use a Java Object in java Script. 嗨,我正在使用Play Framework 2.3,我想在Java脚本中使用Java对象。 For this I tried to use json. 为此,我尝试使用json。 This ist the Object: 这就是对象:

public class List{
protected List<entry> entries = new ArrayList<>();
public void setEntries(entry> entries) {
    this.entries = entries;
}
public void addEntry(Entry entry){
    Entries.add(entry);

public List<List.Entry> getEntry() {
    if (entries == null) {
        entries = new ArrayList<Entry>();
    }
    return this.entries;

} the Entry Class Just contains a double and a String + setter and getter. } Entry类Just包含一个double和一个String + setter和getter。 This is the view in which i wanted to use the object 这是我要使用该对象的视图

@(list: List)
@import play.api.libs.json.Json
@main("VIEW") {
...
<script>
var arr = @Html(Json.toJson(list.getEntry)) ;
...
</script>
} 

I always get the message: "No Json serializer found for type java.util.List[models.List.Entry]. Try to implement an implicit Writes or Format for this type." 我总是收到消息:“找不到类型java.util.List [models.List.Entry]的Json序列化器。尝试为此类型实现隐式Writes或Format。” The only guides and tutorials i could find are for scala but I use java for this. 我只能找到针对scala的指南和教程,但是我为此使用Java。 So kann you explain how i writte a serializer or get the object to javaScript without json? 所以,坎恩,您解释了我如何编写序列化程序或将对象获取到不带json的javaScript吗?

You could write a simple toJson method on your Entry class. 您可以在Entry类上编写一个简单的toJson方法。

public ObjectNode toJson() {
    ObjectNode node = Json.newObject();
    node.put("yourDouble", doubleField);
    node.put("yourString", stringField);
    return node;
}

And then just use it on your entry. 然后在您的输入中使用它。 In the html you could then do something like this: 在html中,您可以执行以下操作:

var arr = @Html(Json.toJson(list.getEntry.map(_.toJson())) ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM