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

时间:2014-04-10 07:58:38

标签: javascript jquery json spring-mvc

我无法从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":"hi@gmail.com","password":"123"}"

我需要实际结果:

{"username":"hi","email":"hi@gmail.com","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;
}

3 个答案:

答案 0 :(得分:5)

尝试

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

答案 1 :(得分:0)

看看写这样的ajax请求是否有帮助。它删除了我认为可能导致问题的显式dataType,并删除了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);
    }
});

答案 2 :(得分: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":"hi@gmail.com","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":"hi@gmail.com","password":"123"}"}
        // The required string : {"d":{username:"hi",email:"hi@gmail.com",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":"hi@gmail.com","password":"123"}"}
        console.log(data.d);                   // output : {"username":"hi","email":"hi@gmail.com","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:"hi@gmail.com",password:"123"}" (correct)
        console.log(content.username);         // output : hi 
        var _name = content.username;
        alert(_name);                         // hi

}