2013-09-05 41 views
4

我有以下問題。 如何將對象列表轉換爲JSON?如何轉換List <Object>到playframework上的JSON 2.1 Java

我試試這個:

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

,但我得到了以下錯誤消息:不兼容的類型

[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 

我究竟做錯了什麼?

以及如何將對象列表轉換爲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); 
    } 
} 

回答

5

對不起,我defeniere返回false型

而不是

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

必須

org.codehaus.jackson.JsonNode json = Json.toJson(plzs); 
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。

相關問題