How to convert List <Object> to JSON in playframework 2.1 Java

I have the following problem. How to convert a 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 a 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); } } 
+4
source share
2 answers

Sorry, I am defeniere false return-type

but not

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

it should be

  org.codehaus.jackson.JsonNode json = Json.toJson(plzs); 
+5
source
 import net.sf.json.JSONObject; .... String resultString = ""; for (QAAsset qaAsset : assetList) { JSONObject jsonObject = JSONObject.fromObject(qaAsset); resultString += "," + jsonObject.toString(); } renderJSON("[" + resultString.substring(1) + "]"); 

I use this method to convert a list of objects to JSON.

0
source

Source: https://habr.com/ru/post/1500721/


All Articles