计算json文件中的特定对象

时间:2017-03-27 03:56:03

标签: java json

以下是阅读权力游戏Json文件的代码。 我已经编写了代码来读取Json文件并将其打印到控制台。 但我想得到季节的数量和文件中出现的剧集数量。但我没有得到理想的输出。

这是示例json内容

 "_embedded": {
"episodes": [
  {
    "id": 4952,
    "url": "http://www.tvmaze.com/episodes/4952/game-of-thrones-1x01-winter-is-coming",
    "name": "Winter is Coming",
    "season": 1,
    "number": 1,
    "airdate": "2011-04-17",
    "airtime": "21:00",
    "airstamp": "2011-04-17T21:00:00-04:00",
    "runtime": 60,
    "image": {
      "medium": "http://static.tvmaze.com/uploads/images/medium_landscape/1/2668.jpg",
      "original": "http://static.tvmaze.com/uploads/images/original_untouched/1/2668.jpg"
    },
    "summary": "\u003cp\u003eLord Eddard Stark, ruler of the North, is summoned to court by his old friend, King Robert Baratheon, to serve as the King\u0027s Hand. Eddard reluctantly agrees after learning of a possible threat to the King\u0027s life. Eddard\u0027s bastard son Jon Snow must make a painful decision about his own future, while in the distant east Viserys Targaryen plots to reclaim his father\u0027s throne, usurped by Robert, by selling his sister in marriage.\u003c/p\u003e",
    "_links": {
      "self": {
        "href": "http://api.tvmaze.com/episodes/4952"
      }
    }
  },

这是我的代码,它将数据读取到控制台但无法从文件中计算特定对象

 package readingdifferentfileformats;

 import java.io.BufferedReader;
 import java.io.FileReader;

 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
 import com.google.gson.JsonArray;
 import com.google.gson.JsonElement;
 import com.google.gson.JsonObject;
 import com.google.gson.JsonParser;

 //Read Json File, and print to console

 public class ReadingGOTJsonFile {

    public static void main(String[] args) {

        JsonParser jsonParser = new JsonParser();

        try {
            BufferedReader br = new BufferedReader(new FileReader("E:\\workspace\\textfile\\got.json"));
            String line;
            while ((line = br.readLine()) != null) {
                JsonObject jsonObject = (JsonObject) jsonParser.parse(line);
                // System.out.println(jsonObject);

                Gson gson = new GsonBuilder().setPrettyPrinting().create();
                String prettyJson = gson.toJson(jsonObject);

                System.out.println(prettyJson);

                JsonArray jsonArray = jsonObject.getAsJsonArray("season");
                for (int i = 0; i < jsonArray.size(); i++) {
                    JsonObject object = jsonArray.getAsJsonObject(i);
                }
                System.out.println(object);



            }
            br.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 }

1 个答案:

答案 0 :(得分:0)

这是我的问题的最终代码

 package readingdifferentfileformats;

 import java.io.File;
 import java.io.FileReader;
 import java.io.FileWriter;
 import java.util.ArrayList;
 import java.util.List;

 import com.google.gson.JsonArray;
 import com.google.gson.JsonElement;
 import com.google.gson.JsonObject;
 import com.google.gson.JsonParser;

 //Read Json File, and print to console

 public class ReadingGOTJsonFile {

public static final String delimiter = ",";
public static final String new_line = "\n";
public static final String Header = "id,url,name,season,number,airdate,airstamp,airtime,runtime,summary";

public static void main(String[] args) {

    JsonParser parser = new JsonParser();
    List<GotClassFile> l = new ArrayList<GotClassFile>();
    try {
        JsonElement jElement = parser.parse(new FileReader(new File("E:\\workspace\\textfile\\got.json")));
        JsonObject jObject = jElement.getAsJsonObject();
        JsonObject embedded = jObject.get("_embedded").getAsJsonObject();
        JsonArray episodes = embedded.get("episodes").getAsJsonArray();

        // System.out.println(jObject);
        // System.out.println(embedded);
        // System.out.println(episodes.size());

        for (JsonElement episode : episodes) {
            JsonObject jsonObject = episode.getAsJsonObject();

            GotClassFile classFile = new GotClassFile(jsonObject.get("id").getAsString(),
                    jsonObject.get("url").getAsString(), jsonObject.get("name").getAsString(),
                    jsonObject.get("season").getAsString(), jsonObject.get("number").getAsString(),
                    jsonObject.get("airdate").getAsString(), jsonObject.get("airstamp").getAsString(),
                    jsonObject.get("airtime").getAsString(), jsonObject.get("runtime").getAsString(),
                    jsonObject.get("summary").toString());
            l.add(classFile);
        }

        FileWriter fileWriter = new FileWriter(new File("E:\\workspace\\textfile\\Got.csv"));
        fileWriter.append(Header);
        fileWriter.append(new_line);

        for (GotClassFile f : l) {

            fileWriter.append("\"" + f.getId() + "\"");
            fileWriter.append(delimiter);
            fileWriter.append("\"" + f.getUrl() + "\"");
            fileWriter.append(delimiter);
            fileWriter.append("\"" + f.getName() + "\"");
            fileWriter.append(delimiter);
            fileWriter.append("\"" + f.getSeason() + "\"");
            fileWriter.append(delimiter);
            fileWriter.append("\"" + f.getNumber() + "\"");
            fileWriter.append(delimiter);
            fileWriter.append("\"" + f.getAirdate() + "\"");
            fileWriter.append(delimiter);
            fileWriter.append("\"" + f.getAirstamp() + "\"");
            fileWriter.append(delimiter);
            fileWriter.append("\"" + f.getAirtime() + "\"");
            fileWriter.append(delimiter);
            fileWriter.append("\"" + f.getRuntime() + "\"");
            fileWriter.append(delimiter);
            fileWriter.append("\"" + f.getsummary() + "\"");
            fileWriter.append(new_line);

        }
        fileWriter.close();
    } catch (Exception e) {
        e.printStackTrace();

    }
}

 }