Forum Discussion

jferrandis's avatar
8 years ago

Convert a string into a json object

Hi all

 

Is there a way to convert a string into a json object.

My case is this one. 

To handle multiple winners in contest, i use the annoucement field where a  i put a formatted message : "{winners:[{id:xx),{id:yy},...],order:true}"

 

when a get the data with an API call, result is a string. The only way to "convert" it a json is to put an ?eval which is quite ugly and causes some freemarker errors

 

Is there custom freemarker builts-in to make this? 

 

Thank you for your help

    • jferrandis's avatar
      jferrandis
      Expert
      Thanks but is this class available in freemarker?
      If not, is there a way to add it ?
      • donpacote's avatar
        donpacote
        Helper

        i put my code

         

        protected <T> T fromJson(byte[] data, Class<T> modelClass) {
        return gson.fromJson(new String(data), modelClass);
        }

         

        protected String toJson(Object object) {
        return gson.toJson(object);
        }

         

        public List makeResponse(HttpResponse httpResponse, LithiumRequest lithiumRequest) {
        return Collections.singletonList(fromJson(httpResponse.getData(), getModelClass()));
        }

  • SuzieH's avatar
    SuzieH
    Khoros Alumni (Retired)

    It looks like you can use ?eval. At least that's what they say on Stack Overflow.

     

    Just be sure to check for null first.

     

    Does this solve your needs?

    • jferrandis's avatar
      jferrandis
      Expert
      i think i read the same post.

      I hoped there was a better solution, something like a number_to_date-like directive or specific built-in in lithium.

      by the way thanks for your contribution