json - 将 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?
解决方案
创建一个类来保存对象。
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/
推荐阅读
- sql - 从同一个表中获取不同ID的一列的值
- java - 在 OnClickListener 中填充并执行 Spinner
- python - python线程具有与fork相同的行为
- cs50 - 自下而上的方法对阅读错误有好处吗
- beagleboneblack - 为什么在 U-boot 中正确进行代码重定位?
- arduino - 在软串行上运行 HM10 是否启用低能耗特性?如果是这样,在这种情况下如何调整 UUID 和 GATT 配置文件?
- security - docker-machine(通用驱动程序)将TCP端口2376打开到互联网是否安全?
- c# - 如何通过在 ASP.NET WebForms 中选择下拉值向现有表的新可空列添加记录?
- c# - 如何将光标设置在绑定到数据表的datagrid中空行的第一个单元格上
- recursion - 在 F# 中使用免费的 monad 是否意味着更长的启动时间和有限的指令?