繁体   English   中英

我无法完全解析 java 中的 JSON

[英]I can't fully parse JSON in java

"movies": [
{
  "name": "Good omens",
  "year": 2019,
  "description": "TV Series",
  "director": {
    "fullName": "Douglas Mackinnon"
  },
  "cast": [
    {
      "fullName": "Michael Sheen",
      "role": "Aziraphale"
    },
    {
      "fullName": "David Tennant",
      "role": "Crowley"
    }
  ]

]

我的读者

public Movie[] getValueOfMovie()throws Exception{
    JSONParser parser = new JSONParser();
    try(FileReader reader = new FileReader("movies.json")){

        JSONObject rootJsonObj = (JSONObject) parser.parse(reader);
        JSONArray moviesJsonArray = (JSONArray)rootJsonObj.get("movies");

        Movie[] films = new Movie[moviesJsonArray.size()];

        Integer q=0;
        for (Object mO: moviesJsonArray){
            JSONObject moviesJsonObj = (JSONObject) mO;
            films[q] = new Movie((String) moviesJsonObj.get("name"),
                    (Long) moviesJsonObj.get("year"),
                    (String) moviesJsonObj.get("description"),
                    (Director) moviesJsonObj.get("director"),
                    (Cast) moviesJsonObj.get("cast"));
            q = q + 1;
        }
        return films;

    }catch(FileNotFoundException e){
        e.printStackTrace();
    }
    return null;
}

我的电影文件

public class Movie {
private String name;
private long year;
private String description;
Director director;
Cast cast;

public Movie(String name, long year, String description, Director director, Cast cast) {
    this.name = name;
    this.year = year;
    this.description = description;
    this.director = director;
    this.cast = cast;
}

我无法正确地传递给导演和演员。 我试着在没有他们的情况下做我的读者,但对于我如何从导演那里获取信息并投给我的读者来说,这真是个问题。 错误是 ClassCastexception(类 org.json.simple.JSONObject 无法转换为 class Director(org.json.simple.JSONObject 和 Director)在未命名的加载程序模块中)

json-simple不知道你的类。 相反,它的 model 由以下类型组成

  • JSONObject
  • JSONArray
  • String
  • Boolean
  • Number

这意味着每次您想要一个不在此列表中的 class 时,您都必须自己构建它。 事实上,您已经使用Movie class 做到了这一点。

films[q] = new Movie((String) moviesJsonObj.get("name"), /* other parameters */ );

等效地,您可以处理像这样的Director class

JSONObject directorJsonObj = (JSONOBject) moviesJsonObj.get("director");
Director director = new Director((String) directorJsonObj.get("fullName");

此外,您正确处理了一系列Movies

JSONArray moviesJsonArray = (JSONArray) rootJsonObj.get("movies");
Movie[] films = new Movie[moviesJsonArray.size()];
Integer q = 0;
for (Object mO : moviesJsonArray) {
    films[q] = new Movie(/* parameters */);
    q = q + 1;
}

这可以转移到一组Actors

JSONArray castJsonArray = (JSONArray) moviesJsonObj.get("cast");
Actor[] cast = new Actor[castJsonArray.size()];
int q = 0;
for (Object obj : moviesJsonArray) {
    cast[q] = new Actor(/* parameters */);
    q++;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM