1

I have a nested JSON which looks like this.

{
"eventId" : "12345",
"eventName" : "carnival",
"object": {
    "objectId" : "5678",
    "objectFiles" : [{"fileName":"text.txt", "fileContent":"This is a test file."},
                    {"fileName":"text2.txt", "fileContent":"This is a test2 file."}]
    }
}

Here I have to fetch the eventFiles key, replace the fileContent value with Base64Encoded String and place it back to the same eventFiles attribute. I know that I can use Jackson Mapper to convert it into Map and iterate them one by one, untill I find eventFiles key, then fetch and replace the value and store it back again. I tried to convert it as a Map using TypeReference<String, Object> or even TypeReference<Map<String, Map<String, Object>>> but the problem here is the nested JSON where ultimately it would become Map inside of a Map inside of a Map which would become pretty complex to handle.

Is there any other simpler way to accomplish this? Any suggestions would be really helpful. Thanks in advance.

1 Answer 1

2

If your Json has a fixed format you can use Gson (https://github.com/google/gson) and convert it to an Object that represent your json.

It would look something like this:

public class CustomEvent {
    String eventId;
    String eventName;
    CustomObject object;
}

public class CustomObject {
    String objectId;
    List<CustomFile> objectFiles;
}

public class CustomFile {
    String fileName;
    String fileContent;
}

And you could use it like this:

Gson gson = new Gson();
CustomEvent event = gson.fromJson(yourString, Event.class)
// Do whatever you want with the event

String modifiedJson = gson.toJson(event);

Hope it helped

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your answer. I would not have a fixed format. It keeps changing. So dynamically I have to accomplish this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.