简体   繁体   English

Java 字符串到 JsonObject 返回 null

[英]Java String to JsonObject returns null

I'm trying to convert String to JSONObject, but always returns null.我正在尝试将 String 转换为 JSONObject,但总是返回 null。

At front page, I used $.ajax to send post data,在首页,我使用$.ajax发送帖子数据,

    var jsonInfo = '{"search_key":"apple", "person":{"name":"test","age":20}}';
    
    var testApi = $.ajax({
        type : "POST", 
        url : "/test/testPerson",
        dataType : "json",
        data : {
            "apiData" : JSON.stringify(jsonInfo)
        }
    })
    .done(function(data, status){
        console.log("success!" + status);
    });

At Servlet, I tried to get the JSONObject with following code:在 Servlet,我尝试使用以下代码获取 JSONObject:

    JSONObject jsonObject = new JSONObject();
    JSONParser parser = new JSONParser();
    Object obj = null;
    try {
        obj = parser.parse(reqApiKey2);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
    jsonObject = (JSONObject) obj;

But I got an error, java.lang.ClassCastException: java.lang.String cannot be cast to org.json.simple.JSONObject at jsonObject = (JSONObject) obj;但是我得到了一个错误, java.lang.ClassCastException: java.lang.String cannot be cast to org.json.simple.JSONObject jsonObject = (JSONObject) obj;

I tried to send the data with JSON.parse(jsonInfo) from web, but same result.我尝试使用JSON.parse(jsonInfo)从 web 发送数据,但结果相同。

Thank you for your advices, and helps.感谢您的建议,并提供帮助。

Your client code is turning the json in the variable jsonInfo into a plain String.您的客户端代码正在将变量jsonInfo转换为纯字符串。 Don't do that - it's already JSON!不要那样做——它已经是JSON 了!

Change:改变:

data : {
    "apiData" : JSON.stringify(jsonInfo)
}

to:至:

data : {
    "apiData" : jsonInfo
}

Your server code is correctly deserializing it as String , not an object.您的服务器代码将其正确反序列化为String ,而不是 object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM