gpt4 book ai didi

java - 我试图在 Java 上使用 gson 将大量自定义对象写入 json 文件,但它在文件完成之前就被切断了?

转载 作者:行者123 更新时间:2023-12-02 01:17:10 24 4
gpt4 key购买 nike

我正在制作一个 Java 程序来从 MTGJson 读取数据,方法是将每张卡保存为自定义类,然后使用 gson 将所有这些卡写入另一个 JSON 文件。 (我发现我无法使用 gson 读取 mtgjson,但可以使用 json.simple。)看来代码以奇怪的顺序读取对象,然后不会将每张卡片保存到列表中,然后在整个卡片之前list是用json写的,突然就断了。 json 文件的下载地址在这里。 https://www.mtgjson.com/json/AllSets.json

import com.google.gson.Gson;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

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

public class DatabaseTrimmer {

public static void main(String[] args) throws IOException, ParseException {
JSONObject ALLSETS = (JSONObject) new JSONParser().parse(new FileReader("AllSets.json"));
List<MTGCard> AllCards = new ArrayList<>();
for(Object o: ALLSETS.values()) {
JSONObject set = (JSONObject)o;
JSONArray cards = (JSONArray) (set.get("cards"));
for (Object card : cards) {
MTGCard tempCard = new MTGCard((JSONObject) card);
if (!tempCard.isReprint) {
AllCards.add(tempCard);
}
}
}
Gson gson = new Gson();
FileWriter writer = new FileWriter("TrimmedAllSets.json");
gson.toJson(AllCards, writer);
}
}

保存到“所有卡牌”列表中的最后一张牌是“沃拉斯的运动传感器”,它是某组牌中的最后一张牌,但不是按字母顺序排列的最后一组牌。 MTGCard 类存储每张卡的许多属性,例如名称和文本。输出 json 的末尾如下所示:

"isReprint":false,"printings":["UGL"]},{"name":"Sorry","type":"Enchantment","text":"Before any player casts a spell with the same name as a card in any graveyard, that player may say \"sorry.\" If they don\u0027t, any other player may say \"sorry\" as the spell is being cast. When another player says \"sorry\" this way, counter the spell.\nWhenever a player says \"sorry\" at any other time, Sorry deals 2 damage to that player.","rarity":"uncommon","manaCost":"{U}{U}","artist":"Kaja Foglio","convertedManaCost":2.0,"isFoil":false,"isReprint":false,"printings":["UGL"]},{"name":"Spark Fiend","type":"Creature — Beast","text":"When Spark Fiend enters the battlefield, roll two six-sided dice. If you rolled 2, 3, or 12, sacrifice Spark Fiend. If you rolled 7 or 11, don\u0027t roll dice for Spark Fiend during any of your following upkeeps. If you rolled any other total, note that total.\nAt the beginning of your upkeep, roll two six-sided dice. If you rolled 7, sacrifice Spark Fiend. If you roll the noted total, don\u0027t roll dice for Spark Fiend during any of your 

如您所见,它就被切断了。我查找了有关 gson 写入限制的任何内容,但找不到任何内容。另外,我尝试让代码从另一点开始,或者阅读更小的部分,但它仍然任意切断。

最佳答案

程序在写入器中的缓冲区刷新到操作系统之前退出。您应该正确刷新编写器或关闭()它。

关于java - 我试图在 Java 上使用 gson 将大量自定义对象写入 json 文件,但它在文件完成之前就被切断了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58370334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com