具有Java json的对象数组

时间:2019-12-04 22:41:59

标签: java arrays json gson

试图使用Java读取对象json数组 这是我的json文件:

 {
    "title": "The Social network",
    "summary": "On a fall night in 2003,Havard undergrad and \n programming genius Mark Zuckerberg sits down at his \n computer and heatedly begins working on a new idea.(...)",
    "year": 2010,
    "director": {
        "last_name": "fincher",
        "first_name": "David"
    },
    "actors": [{
            "first_name": "Jesse",
            "last_name": "Eisenberg"
        },
        {
            "first_name": "Roney",
            "last_name": "Mara"
        }
    ]
}

我上了两堂课


public class film {
private String title;
private String summary;
private int year;
private personne director;
private personne[] actors;

和personne类,都带有getter和setter和简单的tostring方法 这是我的主要学习尝试

public class FilmJsonReader {

    public static final String JSON_FILE="C:\\Users\\hp\\Desktop\\JSON project\\FILM.txt";

    public static void main(String[] args) throws IOException {

        InputStream fis = new FileInputStream(JSON_FILE);

        //create JsonReader object
        JsonReader jsonReader = Json.createReader(fis);

        //get JsonObject from JsonReader
        JsonObject jsonObject = jsonReader.readObject();

        //we can close IO resource and JsonReader now
        jsonReader.close();
        fis.close();

        //Retrieve data from JsonObject and create Employee bean
        film Film = new film();

        Film.setTitle(jsonObject.getString("title"));
        Film.setSummary(jsonObject.getString("summary"));
        Film.setYear(jsonObject.getInt("year"));

        //reading inner object from json object
                JsonObject innerJsonObject = jsonObject.getJsonObject("address");
                personne director = new personne();
                director.setFirst_name(innerJsonObject.getString("first_name"));
                director.setLast_name(innerJsonObject.getString("last_name"));
                Film.setDirector(director);

                //reading arrays from json
        JsonArray jsonArray = jsonObject.getJsonArray("actors");
        personne[] actors = new personne[jsonArray.size()];
        personne p = new personne();
        int i = 0;
        for(JsonValue value : jsonArray){
            actors[i++]=p.toString(value.toString());
        }
        Film.setActors(actors);

        //print employee bean information
        System.out.println(Film);

    }

}

但是这是输出,我在读取数组内部的对象时遇到问题

--------------------------------------

title =社交网络
summary =在2003年的一个秋夜,Havard本科生和(...)
年= 2010
director = fincher,David

** actor = null null **


1 个答案:

答案 0 :(得分:0)

在您的for循环中,您需要为JSON数组中的每个参与者创建一个新的personne对象。您可以执行与创建导演完全相同的方法,然后调用Film.setDirector(director);代替actors[i++]=actor,其中actor是您刚创建的人。希望这会有所帮助