前端特殊字符数据,后端接收产生错乱,前后端都需要处理

发布于:2024-06-27 ⋅ 阅读:(272) ⋅ 点赞:(0)

前端:

const data = {
  createTime: "2024-06-11 09:58:59",
  id: "1800346960914579456",
  merchantId: "1793930010750218240",
  mode: "DEPOSIT",
  channelCode: "if(amount >= 50){'iugu2pay';} else if(amount < 10){'iugupay';} else {'todaypay';}",
  settleRate: 8,
  settleFee: 8,
  conditionSettleRate: "if(amount >= 5){ 0.2;} else{0.88;}",
  name: "HaliAntpay"
};

// Encode the fields
data.channelCode = encodeURIComponent(data.channelCode);
data.conditionSettleRate = encodeURIComponent(data.conditionSettleRate);

// Send the encoded data
fetch('http://your-backend-endpoint/yourEndpoint', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.error('Error:', error));

后端:

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

@RestController
public class YourController {

    @PostMapping("/yourEndpoint")
    public AjaxResult yourMethod(@RequestBody String rawRequestBody) throws IOException {
        System.out.println("Received raw JSON: " + rawRequestBody);

        ObjectMapper mapper = new ObjectMapper();
        MerchantChnlSetting merchantChnlSetting = mapper.readValue(rawRequestBody, MerchantChnlSetting.class);

        // Decode the fields
        String decodedChannelCode = URLDecoder.decode(merchantChnlSetting.getChannelCode(), StandardCharsets.UTF_8.name());
        String decodedConditionSettleRate = URLDecoder.decode(merchantChnlSetting.getConditionSettleRate(), StandardCharsets.UTF_8.name());

        // Set the decoded values back to the object
        merchantChnlSetting.setChannelCode(decodedChannelCode);
        merchantChnlSetting.setConditionSettleRate(decodedConditionSettleRate);

        System.out.println("Mapped Object: " + merchantChnlSetting);
        // Continue processing
        return AjaxResult.success();
    }
}






网站公告

今日签到

点亮在社区的每一天
去签到