无法从 json 字符串中删除双引号

问题描述 投票:0回答:3

我无法从 json 字符串中删除双引号。我的代码如下:

var values = {};
        $.each($('#regForm :input'), function(i, field) {
            if (field.name == "submit") {
                delete field.name;
            } else {
                values[field.name] = field.value; 
            }
        });
        var json_text = JSON.stringify(values);
        var global = JSON.parse(json_text);
        console.log(global);
        $.ajax({
            type : "POST",
            dataType : "JSON",
            data : global,
            url : "http://localhost:8080/SpringRestServices/register",
            beforeSend : function(xhr) {
                xhr.setRequestHeader("Accept", "application/json"); 
                xhr.setRequestHeader("Accept-Encoding", "utf-8");
                xhr.setRequestHeader("Content-type", "application/json");
            },
            success : function(data) {
                alert("success"+data);
                console.log("Success:", data);
            },
            error: function(xhr, textStatus, errorThrown) {
                console.log("HI");
                   alert("Failed to cancel subscription! Message:" + textStatus /*+ jqXHR.errorThrown  + xhr.responseText*/);
                   alert("readyState: " + xhr.readyState);
                   alert("responseText: "+ xhr.responseText);
                   alert("status: " + xhr.status);
                   alert("text status: " + textStatus);
                   alert("error: " + errorThrown);
            }
        });

这是我在 Firefox 调试器中看到的输出:

"{"username":"hi","email":"[email protected]","password":"123"}"

我需要实际结果:

{"username":"hi","email":"[email protected]","password":"123"}

这是我的服务器代码:

@RequestMapping(value = "/register", method = RequestMethod.POST)
@ResponseBody
public RegisterResponse newAccount(@RequestBody Register registration) {
    String newAccountSql = "INSERT INTO register (email,password,username) VALUES (:email,:password,:username)";
    RegisterResponse regResponse = new RegisterResponse();
    regResponse.setResult(-1);
    // ServiceDataBean<AuthToken> retBean = new
    // ServiceDataBean<AuthToken>();
    try {
        System.out.println("register service calling.....");
        MapSqlParameterSource namedParameters = new MapSqlParameterSource();
        namedParameters.addValue("email", registration.getEmail());
        messageDigest = MessageDigest.getInstance("MD5");
        byte[] md5 = new byte[64];
        messageDigest.update(
                registration.getPassword().getBytes("iso-8859-1"), 0,
                registration.getPassword().length());
        md5 = messageDigest.digest();
        namedParameters.addValue("password", convertedToHex(md5));
        namedParameters.addValue("username", registration.getUsername());
        GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();

        // TODO what to do with the updInt also check it's not -1
        int updInt = jdbcTemplate.update(newAccountSql, namedParameters,
                generatedKeyHolder);
        regResponse.setResult(0);
        System.out.println("from register");
    } catch (Throwable e) {
        regResponse.setResult(001);
        e.printStackTrace();
    }
    return regResponse;
}
javascript jquery json spring-mvc
3个回答
5
投票

尝试

json_text= json_text.slice(1, json_text.length-1);

0
投票

看看这样写你的ajax请求是否有帮助。 它删除了我认为可能导致问题的显式数据类型,还删除了 beforeSend 函数并将其替换为内置的 contentType 选项(并删除了显式返回数据类型)。

$.ajax({
    type : "POST",
    data : global, //Or json_text, whichever worked.
    url : "http://localhost:8080/SpringRestServices/register",
    contentType : "application/json",
    success : function(data) {
        alert("success"+data);
        console.log("Success:", data);
    },
    error: function(xhr, textStatus, errorThrown) {
        console.log("HI");
        alert("Failed to cancel subscription! Message:" + textStatus /*+ jqXHR.errorThrown  + xhr.responseText*/);
        alert("readyState: " + xhr.readyState);
        alert("responseText: "+ xhr.responseText);
        alert("status: " + xhr.status);
        alert("text status: " + textStatus);
        alert("error: " + errorThrown);
    }
});

0
投票

我认为不需要替换任何引号,这是一个完美形成的 JSON 字符串,您只需要将 JSON 字符串转换为对象即可。这篇文章完美地解释了这种情况:Link

示例:

success: function (data) {

        // assuming that everything is correct and there is no exception being thrown
        // output string {"d":"{"username":"hi","email":"[email protected]","password":"123"}"}
        // now we need to remove the double quotes (as it will create problem and 
        // if double quotes aren't removed then this JSON string is useless)
        // The output string : {"d":"{"username":"hi","email":"[email protected]","password":"123"}"}
        // The required string : {"d":{username:"hi",email:"[email protected]",password:"123"}"}
        // For security reasons the d is added (indicating the return "data")
        // so actually we need to convert data.d into series of objects
        // Inbuilt function "JSON.Parse" will return streams of objects
        console.log(data);                     // output  : Object {d="{"username":"hi","email":"[email protected]","password":"123"}"}
        console.log(data.d);                   // output : {"username":"hi","email":"[email protected]","password":"123"} (accessing what's stored in "d")
        console.log(data.d[0]);                // output : {  (just accessing the first element of array of "strings")
        var content = JSON.parse(data.d);      // output : Object {username:"hi",email:"[email protected]",password:"123"}" (correct)
        console.log(content.username);         // output : hi 
        var _name = content.username;
        alert(_name);                         // hi

}
© www.soinside.com 2019 - 2024. All rights reserved.