Arunabh
Arunabh

Reputation: 179

Using org.json.JSONObject and Jackson together

public String convertToJson(List<MyModelDTO> modelDTO) {
    com.fasterxml.jackson.databind.ObjectMapper mapper = new ObjectMapper();

    try {
        return mapper.writeValueAsString(modelDTO);
    } catch (JsonGenerationException ex) {
        ex.printStackTrace();
    } catch (JsonMappingException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return null;
}

public Model getDefinition(ModelDTO modelDTO) {
    JsonAjaxModel jsonAjaxModel = new JsonAjaxModel();

    //resultMap is a map to initialise the JSON
    org.json.JSONObject modelStepsJson = new JSONObject(resultMap);
    org.json.JSONObject jsonObj = new JSONObject();
    jsonObj.put("MODELLING_STEPS", modelStepsJson);

    List<MyModelDTO> methodModelList = myDAO.getSavedsteps(MyModelDTO.getModelId());
    jsonObj.put("STEPS", convertToJson(methodModelList));

    jsonAjaxModel.setJsonString(jsonObj.toString());
    return jsonAjaxModel;
}

As seen above I am using Jackson with org.json.JSONObject. The problem is that the final JSON string generated has '' in it which is giving an error while using eval in JavaScript.

{"MODELLING_STEPS":{
    "1":"Data Set,UOM and modelling methodology Selection",
    "2":"Loss Data Frequency modelling"},
"STEPS":"[
    {\\\"stitchingModelId\\\":200844,\\\"modellingStepId\\\":1},
    {\\\"stitchingModelId\\\":200844,\\\"modellingStepId\\\":2}
]

Please note that I cannot use org.json.simple.JSONObject.escape() as my project doesn't allow that.

Hope the question is clear. Please let me know how to escape ''.

Upvotes: 2

Views: 448

Answers (1)

rudi Ladeon
rudi Ladeon

Reputation: 693

I propose not to convert the jsonObj object to a String object. And therefore to replace the line:

jsonAjaxModel.setJsonString(jsonObj.toString ()) 

by a function like:

jsonAjaxModel.setJsonObj(jsonObj);

Upvotes: 1

Related Questions