简体   繁体   中英

Java Json - Reading a file, editing the files values, and then saving the new edits

so I have finally got reading multiple JSON objects and arrays working, with help from (can't post because of reputation...) But I have ran into a problem.. I can't seem to output the changes I've made (setting values of objects). I can only output the changes. Not set the changes in the file I read from, then output the file with the changes.

Also I am using this library (Please use it if you'd like to help): https://mega.co.nz/#!LIkQ1Lwa!Jz0S1zdgYHzcpxpd2spmXxhAxu564Wrp0dUChqnDARU

Here's my code. (It might be messy. But it works for this silly json java thing)

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();
            }

And each time I save a file, this gets outputted:

{ "value": 1, "XP_MULTIPLIER": 100, "CASH_MULTIPLIER": 50, "MAX_HEALTH_MULTIPLIER": 10000, "MIN_HEALTH_MULTIPLIER": 10000, "HEALTH_REGEN_RATE_MULTIPLIER": 10, "MAX_ARMOR_MULTIPLIER": 10000 }

Instead of editing the actual file I read from.

Found here: https://mega.co.nz/#!GMUC3ZqT!JsvNEG5FEKTMsIhlDJdNjHyH7714qH199WmcTxdVO-E

If you are using maven (which I strongly recommend), you must put this in your pom.xml file:

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

This will add jackson as a dependency to your project and maven will handle downloading it and adding it to the build path.

In order to serialize an object to json you need to create an ObjectMapper:

ObjectMapper mapper = new ObjectMapper();

then use its writeValue method which takes a File/OutputStream/Writer as first parameter and Object as second.

mapper.writeValue(myFile, myData);

To deserialize json back to an object, you use the readValue() method, which takes as parameters File/InputStream/Reader and Object type.

For exmaple:

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

If you want to deserialize a collection(in this example a List) you can use

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

To read a Map (HashMap):

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

Arrays:

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

And to modify your data, you can use simple setters/getters and then save again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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