You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中将Component标签传入的Model解析为JSON?

How to Parse a Java DTO into JSON in JavaScript

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:

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);

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:48:47