How to tranform JSON

Viewed 141

I want to transform this JSON:

   {
     "img":"/content/my/image/abc.png",
     "text1":"hello <a href='https://google.com'>world</a>",
     "text2":"hello <a href='/content/mypage.html'>world</a>"  
   }

Expected JSON output:

   {
     "img":"https://myserver.com/content/my/image/abc.png",
     "text1":"hello <a class='external' href='https://google.com'>world</a>" 
     "text2":"hello <a class='internal' href='/content/mypage.html'>world</a>" 
   }

Basically I would like to add css class based on href value. Also add server address if img path is png. I could not find out how to achieve this. I see this but not very much sure it could be possible to do this.

The size of JSON could be around 5 MB which is coming as a response from Java Servlet and I want to transform this before the response is sent to the user.

Could you please suggest some links/examples how to do it?

1 Answers

There is no direct shortcut to convert your value. I assume your input is JSON string and the expected output is JSON string.

you have to divide into 3 parts.

  1. convert JSON string into JAVA object.
  2. your transformation logic on JAVA object and prepare the desired one.
  3. convert JAVA object into JSON string.

Below 2 methods can help you with the conversion of point 1 and point 3. you can put your JAVA logic in between.

public static <T> T convertStringtoJavaObject(String jsonString, Class<T> conversionClass)
    {
        T eee = null;
        try {
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
            objectMapper.addMixIn(JAXBElement.class, JAXBElementMixIn.class);
            if(StringUtils.isNotEmpty(jsonString)){
                com.fasterxml.jackson.databind.JsonNode jsonNode = objectMapper.readTree(jsonString);
                eee = objectMapper.treeToValue(jsonNode, conversionClass);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return eee;
    }

And here is the second one,

public static <T> String convertObjecttoString(T jsonObject, Class<T> conversionClass)
    {
        String eee = null;
        try{
            ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(org.codehaus.jackson.map.SerializationConfig.Feature.USE_ANNOTATIONS, true);

            eee = objectMapper.writeValueAsString(jsonObject);
        }catch(Exception e){
            e.printStackTrace();
        }
        return eee;
    }
Related