将POJO数组转换为JSONObject

时间:2019-02-14 07:35:33

标签: json gson

我的print语句返回以下字符串,其中“电影”是类“电影”的ArrayList。

System.out.print(new Gson().toJson(movies))

O / P

[{"movie_name":"Interstellar11","movie_rating":0.0,"votes_numb":0,"theatreNameList":[],"showTimingList":[]},{"movie_name":"Titanic","movie_rating":0.0,"votes_numb":0,"theatreNameList":[],"showTimingList":[]},{"movie_name":"Titanic66","movie_rating":0.0,"votes_numb":0,"theatreNameList":[],"showTimingList":[]},{"movie_name":"Avatar","movie_rating":0.0,"votes_numb":0,"theatreNameList":[],"showTimingList":[]}]

我想将上面的String转换为JSON。当我将上面的字符串传递给:

JSONObject jsonObj = new JSONObject(new Gson().toJson(movies))

它显示错误为org.json.JSONException: A JSONObject text must begin with '{' at character 1

如何将上述字符串转换为JSONObject?

1 个答案:

答案 0 :(得分:0)

创建一个用于容纳对象的类。

public class Movie_Details{
   private String movie_name;
   private String movie_rating;
   private String votes_numb;
   private ArrayList theatreNameList;
}

然后反序列化如下:

Gson gson = new Gson();
Movie_Details[] movie_details = gson.fromJson(input, Movie_Details[].class); //input is your String
System.out.println(Arrays.toString(movie_details));// Print array.

参考文章: http://blog.patrickbaumann.com/2011/11/gson-array-deserialization/