如何在JavaScript中将Component标签传入的Model解析为JSON?
Ah, I've run into this exact issue before! The problem here is that when you output ${cc.attrs.modelDTO} directly, you're getting the default Java toString() representation of your ChartDTO object—not a valid JSON string. That's why JSON.parse() throws an error on that com.example.dto.ChartDTO@520ff6ee value.
Here's how to fix this properly:
1. Convert the DTO to JSON on the Backend (Recommended Approach)
The cleanest and most maintainable way is to serialize your ChartDTO object into a valid JSON string in your Java code before passing it to the frontend. Use a standard JSON library like Jackson (the most common choice in Java ecosystems) or Gson to handle the serialization.
Example with Jackson:
// 1. Create and populate your ChartDTO instance ChartDTO chartDTO = new ChartDTO(); chartDTO.setChartName("User Engagement"); chartDTO.setDataPoints(List.of(120, 230, 180)); // 2. Serialize the object to a JSON string ObjectMapper objectMapper = new ObjectMapper(); String chartDTOJson = objectMapper.writeValueAsString(chartDTO); // 3. Pass this JSON string as the value for `modelDTO` instead of the raw object // (Update your cc:attribute logic to use this serialized JSON string)
Then in your frontend script:
Since you're now passing a valid JSON structure, you can directly assign it to a JavaScript variable (no need for JSON.parse() if output correctly):
// The JSON string will be parsed directly into a JavaScript object var dto = ${cc.attrs.modelDTO}; // Now you can access properties like: console.log(dto.chartName); // Outputs "User Engagement" console.log(dto.dataPoints); // Outputs [120, 230, 180]
If your backend wraps the JSON string in quotes (making it a string literal), you can safely use JSON.parse():
var dtoString = '${cc.attrs.modelDTO}'; var dto = JSON.parse(dtoString);
2. (Not Recommended) Override toString() in Your DTO
If you can't modify the backend serialization logic for some reason, you could override the toString() method in your ChartDTO to return a valid JSON string. However, this is a hacky approach and error-prone (especially with special characters or nested objects):
@Override public String toString() { return "{\"chartName\":\"" + this.chartName + "\",\"dataPoints\":" + this.dataPoints + "}"; }
Then you could use JSON.parse('${cc.attrs.modelDTO}') in your JavaScript. But avoid this for production code—it's hard to maintain and easy to break.
内容的提问来源于stack exchange,提问作者Trương Huy

