Home > OS >  How to change json value containing hyphens in Java?
How to change json value containing hyphens in Java?

Time:10-20

Here is my json file

    {
  "file-list":[
    "ab3bdc2c3d-f2fg63-42c3-abasd53-e78c66afc77d"
  ],
  "metadata":{
    "X-Object-Meta-Favourite":"true"
  }
}

So i want to change "X-Object-Meta-Favourite":"true" 's value to false.

First i read

public static JSONObject favourite() throws IOException {

    String body = new String(Files.readAllBytes(Paths.get("src/test/resources/config/environments/FileSystem/Favourite.json")));
        return new JSONObject(body);
    
    }

And it returns JSONObject. So i use this body int his method:

public void fovurite(String action) throws IOException {

    action = "false";

    JSONObject body = readFiles.favourite();
    body.put(body.getJSONObject("metadata").getString("X-Object-Meta-Favourite"),action);

But added true = "false" value. I couldnt change X-Object-Meta-Favourite ' value.

I also tried body.put("metadata['X-Object-Meta-Favourite']",action) but this time added metadata['X-Object-Meta-Favourite'] = "false"

In short how can i change this value ? Thank you for your advice

CodePudding user response:

You are reading the value of the X-Object-Meta-Favourite and putting action in a field of said value, so basically you are putting "false" inside a field named "true", what you want to do is to get the nested object, modify it and put it in a field named metadata.

so it wold be something like:

JSONObject body = readFiles.favourite();
JSONObject nested = body.getJSONObject("metadata");
nested.put("X-Object-Meta-Favourite", action);
body.put("metadata", nested);

I have not tested the code but I hope you understand what I mean.

CodePudding user response:

Instead of this

body.put(body.getJSONObject("metadata").getString("X-Object-Meta-Favourite"),action);

Used this one

body.getJSONObject("metadata").put("X-Object-Meta-Favourite", action);
  • Related