首页 > 解决方案 > 将 POJO 数组转换为 JSONObject

问题描述

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

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

输出/输出

[{"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":[]}]

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

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

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

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

标签: jsongson

解决方案


创建一个类来保存对象。

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/


推荐阅读