Java Json - 读取文件,编辑文件值,然后保存新编辑

时间:2013-12-14 17:32:29

标签: java json file

所以我终于阅读了多个JSON对象和数组工作,在帮助下(因为声誉无法发布...)但是我遇到了一个问题..我似乎无法输出更改我已经制作(设置对象的值)。我只能输出更改。不在我读取的文件中设置更改,然后输出带有更改的文件。

此外我正在使用此库(如果您想提供帮助,请使用它):https://mega.co.nz/#!LIkQ1Lwa!Jz0S1zdgYHzcpxpd2spmXxhAxu564Wrp0dUChqnDARU

这是我的代码。 (它可能很混乱。但它适用于这个愚蠢的json java事物)

try {
                BufferedReader in = new BufferedReader(new InputStreamReader(ModBox.class.getResourceAsStream("/info/lynxaa/modbox/res/tunables.json")));

                String line;
                String out = "";
                while ((line = in.readLine()) != null) {
                    out += line;
                }

                in.close();

                JsonObject object = JsonObject.readFrom(out);
                JsonObject ssObj = object.get("tunables").asObject();
                JsonObject sssObj = ssObj.get("MP_GLOBAL").asObject();

                JsonArray array = null;
                //Fields we want to modify
                String[] arrayObjects = {
                        "CARMOD_SHOP_MULTIPLIER",
                        "CLOTHES_SHOP_MULTIPLIER",
                        "HAIRDO_SHOP_MULTIPLIER",
                        "TATTOO_SHOP_MULTIPLIER",
                        "WEAPONS_SHOP_MULTIPLIER",
                        "CARS_WEBSITE_MULTIPLIER",
                        "PLANES_WEBSITE_MULTIPLIER",
                        "HELIS_WEBSITE_MULTIPLIER",
                        "BOATS_WEBSITE_MULTIPLIER",
                        "BIKES_WEBSITE_MULTIPLIER",
                        "XP_MULTIPLIER",
                        "CASH_MULTIPLIER",
                        "MAX_CASH_GIFT_LIMIT",
                        "MAX_HEALTH_MULTIPLIER",
                        "MIN_HEALTH_MULTIPLIER",
                        "HEALTH_REGEN_RATE_MULTIPLIER",
                        "HEALTH_REGEN_MAX_MULTIPLIER",
                        "MAX_ARMOR_MULTIPLIER"
                };

                final String DIR_ = System.getProperty("user.home") + File.separator + "Desktop" + File.separator + "MODBOX" + File.separator;

                File output = new File(DIR_ + "gta_v_modbox_json" + new Random().nextInt(999) + ".json");
                output.getParentFile().mkdirs();
                output.createNewFile();

                if (output.exists()) {
                    textArea.append("Created MODBOX files: " + output.getAbsolutePath() + "\n");
                }

                for (String objects : arrayObjects) {
                    array = sssObj.get(objects).asArray();
                }

                if (array == null) {
                    textArea.append("Error! Json Array outputted null.");
                    return;
                }

                for (JsonValue value : array.values()) {
                    double mvalue = value.asObject().get("value").asDouble();

                    for (String objss : arrayObjects) {
                        textArea.append(objss + ":" + mvalue + "\n");

                        for (Component component : tabMain.getComponents()) {
                            if (component instanceof JTextField) {
                                JTextField field = ((JTextField) component);

                                if (field.getName() == objss) {
                                    textArea.append("Found match for: " + field.getName());
                                    textArea.append("Setting value of: " + field.getName() + " to: " + Double.parseDouble(field.getText()));
                                    value.asObject().add(objss, Double.parseDouble(field.getText()));

                                    FileWriter fw = new FileWriter(output.getAbsoluteFile());
                                    BufferedWriter bw = new BufferedWriter(fw);

                                    value.writeTo(bw);
                                    bw.close();
                                    break;
                                }
                            }
                        }
                    }
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (NullPointerException e) {
                e.printStackTrace();
            }

每次保存文件时,都会输出:

{   “价值”:1,   “XP_MULTIPLIER”:100,   “CASH_MULTIPLIER”:50,   “MAX_HEALTH_MULTIPLIER”:10000,   “MIN_HEALTH_MULTIPLIER”:10000,   “HEALTH_REGEN_RATE_MULTIPLIER”:10,   “MAX_ARMOR_MULTIPLIER”:10000 }

而不是编辑我读取的实际文件。

在这里找到: https://mega.co.nz/#!GMUC3ZqT!JsvNEG5FEKTMsIhlDJdNjHyH7714qH199WmcTxdVO-E

1 个答案:

答案 0 :(得分:0)

如果您使用的是maven(我强烈推荐),您必须将它放在pom.xml文件中:

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.3.0</version>
</dependency>

这将添加jackson作为项目的依赖项,maven将处理下载并将其添加到构建路径。

为了将对象序列化为json,您需要创建一个ObjectMapper:

ObjectMapper mapper = new ObjectMapper();

然后使用其writeValue方法,该方法将File / OutputStream / Writer作为第一个参数,将Object作为第二个参数。

mapper.writeValue(myFile, myData);

要将json反序列化回对象,可以使用readValue()方法,该方法将File / InputStream / Reader和Object类型作为参数。

例如:

MyClass data = mapper.readValue(myFile, MyClass.class);

如果要反序列化集合(在此示例中为List),可以使用

CollectionType ct = mapper.getTypeFactory().constructCollectionType(List.class,MyClass.class);
List<MyClass> myList = mapper.readValue(myFile, ct);

读取地图(HashMap):

MapType mapType = objectMapper.getTypeFactory().constructMapType(HashMap.class, KeyClass.class, ValueClass.class);
            final Map<KeyClass, ValueClass> data = objectMapper.readValue(myFile, mapType);

阵列:

Data[] data = objectMapper.readValue(myFile, Data[].class);

要修改数据,您可以使用简单的setter / getters然后再次保存。