4

I have the following problem. How can I convert the list of objects to JSON?

I try this:

List<PLZ> plzs = PLZ.findPlz(plz);      
String json = play.libs.Json.toJson(plzs);

but I get the following error message: incompatible types

[Autocomplete] $ compile
[info] Compiling 1 Java source to C:\Entwicklungsumgebung\play-2.1.3\Autocomplete\target\scala-2.10\classes...
[error] C:\Entwicklungsumgebung\play-2.1.3\Autocomplete\app\controllers\Application.java:25: error: incompatible types
[error]                 String json = play.libs.Json.toJson(plzs);
[error]                                                    ^
[error]   required: String
[error]   found:    JsonNode
[error] 1 error
[error] (compile:compile) javac returned nonzero exit code
[error] Total time: 1 s, completed 05.09.2013 13:58:08

what am I doing wrong?

and how can I convert the list of objects to JSON?

package models;

import java.util.*;
import javax.persistence.*;

import play.db.ebean.*;
import play.data.format.*;
import play.data.validation.*;

@Entity
public class PLZ extends Model {

  @Id
  public Long id;

  public String plz;

  public String beschreibung1;

  public String beschreibung2;  


  public static Finder<Long,PLZ> find = new Finder(Long.class, PLZ.class);

  public static List<PLZ> findPlz(String plz){
    List<PLZ> plzs = find.where().ilike("plz", plz+"%").findList();
    return plzs;
  }
 }




package controllers;

import play.libs.Json;
import java.util.*;
import play.*;
import play.mvc.*;
import models.*;

import views.html.*;

public class Application extends Controller {  

    @BodyParser.Of(play.mvc.BodyParser.Json.class)
    public static Result findPlz(String plz) {
        List<PLZ> plzs = PLZ.findPlz(plz);

        String json = play.libs.Json.toJson(plzs);  

        return ok(json);
    }
}

Use COUNT(1) instead:

SELECT engine, COUNT(1) AS count
FROM visits
GROUP BY engine
ORDER BY count DESC;
4

2 回答 2

6

对不起,我拒绝错误的返回类型

而不是

 String json = play.libs.Json.toJson(plzs);

一定是

 org.codehaus.jackson.JsonNode json = Json.toJson(plzs);
于 2013-09-05T12:51:59.830 回答
0
import net.sf.json.JSONObject;
....
String resultString = "";
for (QAAsset qaAsset : assetList) {
  JSONObject jsonObject = JSONObject.fromObject(qaAsset);
  resultString += "," + jsonObject.toString();
}
renderJSON("[" + resultString.substring(1) + "]");

我使用这种方式将对象列表转换为 JSON。

于 2013-09-06T07:57:29.823 回答