0

I am looking for a way to transform a value during parse.

I have base64 encoded content inside a json formatted string with dynamic keys.

{
    "key0": "irrelevant",
    "key1": "VXNlbGVzcyBiYXNlNjQgY29udGVudA==",
    "key2": "QW5vdGhlciBVc2VsZXNzIGJhc2U2NCBjb250ZW50",
    "key3": {
        "key4": "b25lIG1vcmUgVXNlbGVzcyBiYXNlNjQgY29udGVudA==",
        "key5": "irrelevant",
        "key6": {
            "key7": "b25lIG1vcmUgdXNlbGVzcyBiYXNlNjQgc3RyaW5n",
            "key8": "dXNlbGVzcyBiYXNlNjQgc3RyaW5n",
            "key9": "TGFzdCB1c2VsZXNzIGJhc2U2NCBzdHJpbmcsIGJ1dCB0aGVyZSBjb3VsZCBiZSBtb3Jl"
        }
    }
}

I would like to replace the base64 content with a string and end up with something like this:

{
    "key0": "irrelevant",
    "key1": "replaced base64",
    "key2": "replaced base64",
    "key3": {
        "key4": "replaced base64",
        "key5": "irrelevant",
        "key6": {
            "key7": "replaced base64",
            "key8": "replaced base64",
            "key9": "replaced base64"
        }
    }
}

Javascript's JSON.parse method has the concept of a reviver function. Which I am aware that a "reviver" is a Javascript concept, however I am looking for something similar in Java. Here is an example of how it works on Javascript.

  1. https://stackoverflow.com/a/24374222/6076761
  2. https://stackoverflow.com/a/44911097

I am currently using Gson to parse the string to JsonElement.

NB: I do not have any information about the class type for this json string.

I know I could potentially parse the string to JsonObject and then possibly check for these strings recursively after.

However if someone knows of a way that I can do this during parse, please assist.

  • Does this answer your question? [Parsing JSON string in Java](https://stackoverflow.com/questions/11874919/parsing-json-string-in-java) – evolutionxbox May 16 '22 at 14:47
  • thanks for the suggestions. @PetterFriberg I am currently using gson's "JsonParser.parseString" to parse a string to JsonElement. The provided link on a gson solution transforms JsonElement to User. Are you suggesting that I write a custom deserializer from JsonElement to JsonElement ? – Ivhani Maselesele May 16 '22 at 16:05
  • Hi Ivhani, basically there is nothing exactly like a reviver function, but you could fairly easy implement it for example using the JsonReader or JsonDeserializer. is this the best solution in your case?, not sure, you need to evaluate this. I will vote to reopen since I think the question is narrow enough now to be answered, maybe a duplicate of this https://stackoverflow.com/questions/10786536/does-androids-json-parser-support-revivers/ since android uses similar version of gson, but yeah that it's in android and I think that/this question could benefit from an answer showing how to do it. – Petter Friberg May 17 '22 at 13:20
  • 1
    @DavidConrad it's open again if you like to answer. – Petter Friberg May 17 '22 at 13:41

0 Answers0